下面列出了javax.persistence.SequenceGenerator#org.hibernate.id.PersistentIdentifierGenerator 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void interpretSequenceGenerator(
SequenceGenerator sequenceGeneratorAnnotation,
IdentifierGeneratorDefinition.Builder definitionBuilder) {
definitionBuilder.setName( sequenceGeneratorAnnotation.name() );
definitionBuilder.setStrategy( SequenceStyleGenerator.class.getName() );
if ( !BinderHelper.isEmptyAnnotationValue( sequenceGeneratorAnnotation.catalog() ) ) {
definitionBuilder.addParam(
PersistentIdentifierGenerator.CATALOG,
sequenceGeneratorAnnotation.catalog()
);
}
if ( !BinderHelper.isEmptyAnnotationValue( sequenceGeneratorAnnotation.schema() ) ) {
definitionBuilder.addParam(
PersistentIdentifierGenerator.SCHEMA,
sequenceGeneratorAnnotation.schema()
);
}
if ( !BinderHelper.isEmptyAnnotationValue( sequenceGeneratorAnnotation.sequenceName() ) ) {
definitionBuilder.addParam(
SequenceStyleGenerator.SEQUENCE_PARAM,
sequenceGeneratorAnnotation.sequenceName()
);
}
definitionBuilder.addParam(
SequenceStyleGenerator.INCREMENT_PARAM,
String.valueOf( sequenceGeneratorAnnotation.allocationSize() )
);
definitionBuilder.addParam(
SequenceStyleGenerator.INITIAL_PARAM,
String.valueOf( sequenceGeneratorAnnotation.initialValue() )
);
}
public void validateSchema(Dialect dialect, DatabaseMetadata databaseMetadata)
throws HibernateException {
secondPassCompile();
String defaultCatalog = properties.getProperty( Environment.DEFAULT_CATALOG );
String defaultSchema = properties.getProperty( Environment.DEFAULT_SCHEMA );
Iterator iter = getTableMappings();
while ( iter.hasNext() ) {
Table table = (Table) iter.next();
if ( table.isPhysicalTable() ) {
TableMetadata tableInfo = databaseMetadata.getTableMetadata(
table.getName(),
( table.getSchema() == null ) ? defaultSchema : table.getSchema(),
( table.getCatalog() == null ) ? defaultCatalog : table.getCatalog(),
table.isQuoted());
if ( tableInfo == null ) {
throw new HibernateException( "Missing table: " + table.getName() );
}
else {
table.validateColumns( dialect, mapping, tableInfo );
}
}
}
iter = iterateGenerators( dialect );
while ( iter.hasNext() ) {
PersistentIdentifierGenerator generator = (PersistentIdentifierGenerator) iter.next();
Object key = generator.generatorKey();
if ( !databaseMetadata.isSequence( key ) && !databaseMetadata.isTable( key ) ) {
throw new HibernateException( "Missing sequence or table: " + key );
}
}
}
/**
* apply an id generator to a SimpleValue
*/
public static void makeIdGenerator(
SimpleValue id,
XProperty idXProperty,
String generatorType,
String generatorName,
MetadataBuildingContext buildingContext,
Map<String, IdentifierGeneratorDefinition> localGenerators) {
log.debugf( "#makeIdGenerator(%s, %s, %s, %s, ...)", id, idXProperty, generatorType, generatorName );
Table table = id.getTable();
table.setIdentifierValue( id );
//generator settings
id.setIdentifierGeneratorStrategy( generatorType );
Properties params = new Properties();
//always settable
params.setProperty(
PersistentIdentifierGenerator.TABLE, table.getName()
);
final String implicitCatalogName = buildingContext.getBuildingOptions().getMappingDefaults().getImplicitCatalogName();
if ( implicitCatalogName != null ) {
params.put( PersistentIdentifierGenerator.CATALOG, implicitCatalogName );
}
final String implicitSchemaName = buildingContext.getBuildingOptions().getMappingDefaults().getImplicitSchemaName();
if ( implicitSchemaName != null ) {
params.put( PersistentIdentifierGenerator.SCHEMA, implicitSchemaName );
}
if ( id.getColumnSpan() == 1 ) {
params.setProperty(
PersistentIdentifierGenerator.PK,
( (org.hibernate.mapping.Column) id.getColumnIterator().next() ).getName()
);
}
// YUCK! but cannot think of a clean way to do this given the string-config based scheme
params.put( PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, buildingContext.getObjectNameNormalizer() );
params.put( IdentifierGenerator.GENERATOR_NAME, generatorName );
if ( !isEmptyAnnotationValue( generatorName ) ) {
//we have a named generator
IdentifierGeneratorDefinition gen = getIdentifierGenerator(
generatorName,
idXProperty,
localGenerators,
buildingContext
);
if ( gen == null ) {
throw new AnnotationException( "Unknown named generator (@GeneratedValue#generatorName): " + generatorName );
}
//This is quite vague in the spec but a generator could override the generate choice
String identifierGeneratorStrategy = gen.getStrategy();
//yuk! this is a hack not to override 'AUTO' even if generator is set
final boolean avoidOverriding =
identifierGeneratorStrategy.equals( "identity" )
|| identifierGeneratorStrategy.equals( "seqhilo" )
|| identifierGeneratorStrategy.equals( MultipleHiLoPerTableGenerator.class.getName() );
if ( generatorType == null || !avoidOverriding ) {
id.setIdentifierGeneratorStrategy( identifierGeneratorStrategy );
}
//checkIfMatchingGenerator(gen, generatorType, generatorName);
for ( Object o : gen.getParameters().entrySet() ) {
Map.Entry elt = (Map.Entry) o;
if ( elt.getKey() == null ) {
continue;
}
params.setProperty( (String) elt.getKey(), (String) elt.getValue() );
}
}
if ( "assigned".equals( generatorType ) ) {
id.setNullValue( "undefined" );
}
id.setIdentifierGeneratorProperties( params );
}
private static IdentifierGeneratorDefinition buildIdGenerator(
java.lang.annotation.Annotation generatorAnn,
MetadataBuildingContext context) {
if ( generatorAnn == null ) {
return null;
}
IdentifierGeneratorDefinition.Builder definitionBuilder = new IdentifierGeneratorDefinition.Builder();
if ( context.getMappingDefaults().getImplicitSchemaName() != null ) {
definitionBuilder.addParam(
PersistentIdentifierGenerator.SCHEMA,
context.getMappingDefaults().getImplicitSchemaName()
);
}
if ( context.getMappingDefaults().getImplicitCatalogName() != null ) {
definitionBuilder.addParam(
PersistentIdentifierGenerator.CATALOG,
context.getMappingDefaults().getImplicitCatalogName()
);
}
if ( generatorAnn instanceof TableGenerator ) {
context.getBuildingOptions().getIdGenerationTypeInterpreter().interpretTableGenerator(
(TableGenerator) generatorAnn,
definitionBuilder
);
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Add table generator with name: {0}", definitionBuilder.getName() );
}
}
else if ( generatorAnn instanceof SequenceGenerator ) {
context.getBuildingOptions().getIdGenerationTypeInterpreter().interpretSequenceGenerator(
(SequenceGenerator) generatorAnn,
definitionBuilder
);
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Add sequence generator with name: {0}", definitionBuilder.getName() );
}
}
else if ( generatorAnn instanceof GenericGenerator ) {
GenericGenerator genGen = ( GenericGenerator ) generatorAnn;
definitionBuilder.setName( genGen.name() );
definitionBuilder.setStrategy( genGen.strategy() );
Parameter[] params = genGen.parameters();
for ( Parameter parameter : params ) {
definitionBuilder.addParam( parameter.name(), parameter.value() );
}
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Add generic generator with name: {0}", definitionBuilder.getName() );
}
}
else {
throw new AssertionFailure( "Unknown Generator annotation: " + generatorAnn );
}
return definitionBuilder.build();
}
@Override
public IdentifierGenerator createIdentifierGenerator(
IdentifierGeneratorFactory identifierGeneratorFactory,
Dialect dialect,
String defaultCatalog,
String defaultSchema,
RootClass rootClass) throws MappingException {
if ( identifierGenerator != null ) {
return identifierGenerator;
}
Properties params = new Properties();
//if the hibernate-mapping did not specify a schema/catalog, use the defaults
//specified by properties - but note that if the schema/catalog were specified
//in hibernate-mapping, or as params, they will already be initialized and
//will override the values set here (they are in identifierGeneratorProperties)
if ( defaultSchema!=null ) {
params.setProperty(PersistentIdentifierGenerator.SCHEMA, defaultSchema);
}
if ( defaultCatalog!=null ) {
params.setProperty(PersistentIdentifierGenerator.CATALOG, defaultCatalog);
}
//pass the entity-name, if not a collection-id
if (rootClass!=null) {
params.setProperty( IdentifierGenerator.ENTITY_NAME, rootClass.getEntityName() );
params.setProperty( IdentifierGenerator.JPA_ENTITY_NAME, rootClass.getJpaEntityName() );
}
//init the table here instead of earlier, so that we can get a quoted table name
//TODO: would it be better to simply pass the qualified table name, instead of
// splitting it up into schema/catalog/table names
String tableName = getTable().getQuotedName(dialect);
params.setProperty( PersistentIdentifierGenerator.TABLE, tableName );
//pass the column name (a generated id almost always has a single column)
String columnName = ( (Column) getColumnIterator().next() ).getQuotedName(dialect);
params.setProperty( PersistentIdentifierGenerator.PK, columnName );
if (rootClass!=null) {
StringBuilder tables = new StringBuilder();
Iterator iter = rootClass.getIdentityTables().iterator();
while ( iter.hasNext() ) {
Table table= (Table) iter.next();
tables.append( table.getQuotedName(dialect) );
if ( iter.hasNext() ) {
tables.append(", ");
}
}
params.setProperty( PersistentIdentifierGenerator.TABLES, tables.toString() );
}
else {
params.setProperty( PersistentIdentifierGenerator.TABLES, tableName );
}
if (identifierGeneratorProperties!=null) {
params.putAll(identifierGeneratorProperties);
}
// TODO : we should pass along all settings once "config lifecycle" is hashed out...
final ConfigurationService cs = metadata.getMetadataBuildingOptions().getServiceRegistry()
.getService( ConfigurationService.class );
params.put(
AvailableSettings.PREFER_POOLED_VALUES_LO,
cs.getSetting( AvailableSettings.PREFER_POOLED_VALUES_LO, StandardConverters.BOOLEAN, false )
);
if ( cs.getSettings().get( AvailableSettings.PREFERRED_POOLED_OPTIMIZER ) != null ) {
params.put(
AvailableSettings.PREFERRED_POOLED_OPTIMIZER,
cs.getSettings().get( AvailableSettings.PREFERRED_POOLED_OPTIMIZER )
);
}
identifierGeneratorFactory.setDialect( dialect );
identifierGenerator = identifierGeneratorFactory.createIdentifierGenerator( identifierGeneratorStrategy, getType(), params );
return identifierGenerator;
}
private void makeIdentifier(
final MappingDocument sourceDocument,
IdentifierGeneratorDefinition generator,
String unsavedValue,
SimpleValue identifierValue) {
if ( generator != null ) {
String generatorName = generator.getStrategy();
Properties params = new Properties();
// see if the specified generator name matches a registered <identifier-generator/>
IdentifierGeneratorDefinition generatorDef = sourceDocument.getMetadataCollector().getIdentifierGenerator( generatorName );
if ( generatorDef != null ) {
generatorName = generatorDef.getStrategy();
params.putAll( generatorDef.getParameters() );
}
identifierValue.setIdentifierGeneratorStrategy( generatorName );
// YUCK! but cannot think of a clean way to do this given the string-config based scheme
params.put( PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, objectNameNormalizer);
if ( database.getDefaultNamespace().getPhysicalName().getSchema() != null ) {
params.setProperty(
PersistentIdentifierGenerator.SCHEMA,
database.getDefaultNamespace().getPhysicalName().getSchema().render( database.getDialect() )
);
}
if ( database.getDefaultNamespace().getPhysicalName().getCatalog() != null ) {
params.setProperty(
PersistentIdentifierGenerator.CATALOG,
database.getDefaultNamespace().getPhysicalName().getCatalog().render( database.getDialect() )
);
}
params.putAll( generator.getParameters() );
identifierValue.setIdentifierGeneratorProperties( params );
}
identifierValue.getTable().setIdentifierValue( identifierValue );
if ( StringHelper.isNotEmpty( unsavedValue ) ) {
identifierValue.setNullValue( unsavedValue );
}
else {
if ( "assigned".equals( identifierValue.getIdentifierGeneratorStrategy() ) ) {
identifierValue.setNullValue( "undefined" );
}
else {
identifierValue.setNullValue( null );
}
}
}
@Override
public void interpretTableGenerator(
TableGenerator tableGeneratorAnnotation,
IdentifierGeneratorDefinition.Builder definitionBuilder) {
definitionBuilder.setName( tableGeneratorAnnotation.name() );
definitionBuilder.setStrategy( MultipleHiLoPerTableGenerator.class.getName() );
if ( !BinderHelper.isEmptyAnnotationValue( tableGeneratorAnnotation.table() ) ) {
definitionBuilder.addParam(
MultipleHiLoPerTableGenerator.ID_TABLE,
tableGeneratorAnnotation.table()
);
}
if ( !BinderHelper.isEmptyAnnotationValue( tableGeneratorAnnotation.catalog() ) ) {
definitionBuilder.addParam(
PersistentIdentifierGenerator.CATALOG,
tableGeneratorAnnotation.catalog()
);
}
if ( !BinderHelper.isEmptyAnnotationValue( tableGeneratorAnnotation.schema() ) ) {
definitionBuilder.addParam(
PersistentIdentifierGenerator.SCHEMA,
tableGeneratorAnnotation.schema()
);
}
if ( !BinderHelper.isEmptyAnnotationValue( tableGeneratorAnnotation.pkColumnName() ) ) {
definitionBuilder.addParam(
MultipleHiLoPerTableGenerator.PK_COLUMN_NAME,
tableGeneratorAnnotation.pkColumnName()
);
}
if ( !BinderHelper.isEmptyAnnotationValue( tableGeneratorAnnotation.valueColumnName() ) ) {
definitionBuilder.addParam(
MultipleHiLoPerTableGenerator.VALUE_COLUMN_NAME,
tableGeneratorAnnotation.valueColumnName()
);
}
if ( !BinderHelper.isEmptyAnnotationValue( tableGeneratorAnnotation.pkColumnValue() ) ) {
definitionBuilder.addParam(
MultipleHiLoPerTableGenerator.PK_VALUE_NAME,
tableGeneratorAnnotation.pkColumnValue()
);
}
definitionBuilder.addParam(
MultipleHiLoPerTableGenerator.MAX_LO,
String.valueOf( tableGeneratorAnnotation.allocationSize() - 1 )
);
// TODO : implement unique-constraint support
if ( tableGeneratorAnnotation.uniqueConstraints() != null
&& tableGeneratorAnnotation.uniqueConstraints().length > 0 ) {
log.ignoringTableGeneratorConstraints( tableGeneratorAnnotation.name() );
}
}
@Override
public void interpretTableGenerator(
TableGenerator tableGeneratorAnnotation,
IdentifierGeneratorDefinition.Builder definitionBuilder) {
definitionBuilder.setName( tableGeneratorAnnotation.name() );
definitionBuilder.setStrategy( org.hibernate.id.enhanced.TableGenerator.class.getName() );
definitionBuilder.addParam( org.hibernate.id.enhanced.TableGenerator.CONFIG_PREFER_SEGMENT_PER_ENTITY, "true" );
if ( !BinderHelper.isEmptyAnnotationValue( tableGeneratorAnnotation.catalog() ) ) {
definitionBuilder.addParam( PersistentIdentifierGenerator.CATALOG, tableGeneratorAnnotation.catalog() );
}
if ( !BinderHelper.isEmptyAnnotationValue( tableGeneratorAnnotation.schema() ) ) {
definitionBuilder.addParam( PersistentIdentifierGenerator.SCHEMA, tableGeneratorAnnotation.schema() );
}
if ( !BinderHelper.isEmptyAnnotationValue( tableGeneratorAnnotation.table() ) ) {
definitionBuilder.addParam(
org.hibernate.id.enhanced.TableGenerator.TABLE_PARAM,
tableGeneratorAnnotation.table()
);
}
if ( !BinderHelper.isEmptyAnnotationValue( tableGeneratorAnnotation.pkColumnName() ) ) {
definitionBuilder.addParam(
org.hibernate.id.enhanced.TableGenerator.SEGMENT_COLUMN_PARAM,
tableGeneratorAnnotation.pkColumnName()
);
}
if ( !BinderHelper.isEmptyAnnotationValue( tableGeneratorAnnotation.pkColumnValue() ) ) {
definitionBuilder.addParam(
org.hibernate.id.enhanced.TableGenerator.SEGMENT_VALUE_PARAM,
tableGeneratorAnnotation.pkColumnValue()
);
}
if ( !BinderHelper.isEmptyAnnotationValue( tableGeneratorAnnotation.valueColumnName() ) ) {
definitionBuilder.addParam(
org.hibernate.id.enhanced.TableGenerator.VALUE_COLUMN_PARAM,
tableGeneratorAnnotation.valueColumnName()
);
}
definitionBuilder.addParam(
org.hibernate.id.enhanced.TableGenerator.INCREMENT_PARAM,
String.valueOf( tableGeneratorAnnotation.allocationSize() )
);
// See comment on HHH-4884 wrt initialValue. Basically initialValue is really the stated value + 1
definitionBuilder.addParam(
org.hibernate.id.enhanced.TableGenerator.INITIAL_PARAM,
String.valueOf( tableGeneratorAnnotation.initialValue() + 1 )
);
// TODO : implement unique-constraint support
if ( tableGeneratorAnnotation.uniqueConstraints() != null
&& tableGeneratorAnnotation.uniqueConstraints().length > 0 ) {
log.ignoringTableGeneratorConstraints( tableGeneratorAnnotation.name() );
}
}
@SuppressWarnings("unchecked")
protected void bindSimpleId(PersistentProperty identifier, RootClass entity,
InFlightMetadataCollector mappings, Identity mappedId, String sessionFactoryBeanName) {
Mapping mapping = getMapping(identifier.getOwner());
boolean useSequence = mapping != null && mapping.isTablePerConcreteClass();
// create the id value
SimpleValue id = new SimpleValue(metadataBuildingContext, entity.getTable());
Property idProperty = new Property();
idProperty.setName(identifier.getName());
idProperty.setValue(id);
entity.setDeclaredIdentifierProperty(idProperty);
// set identifier on entity
Properties params = new Properties();
entity.setIdentifier(id);
if (mappedId == null) {
// configure generator strategy
id.setIdentifierGeneratorStrategy(useSequence ? "sequence-identity" : "native");
} else {
String generator = mappedId.getGenerator();
if("native".equals(generator) && useSequence) {
generator = "sequence-identity";
}
id.setIdentifierGeneratorStrategy(generator);
params.putAll(mappedId.getParams());
if(params.containsKey(SEQUENCE_KEY)) {
params.put(SequenceStyleGenerator.SEQUENCE_PARAM, params.getProperty(SEQUENCE_KEY));
}
if ("assigned".equals(generator)) {
id.setNullValue("undefined");
}
}
String schemaName = getSchemaName(mappings);
String catalogName = getCatalogName(mappings);
params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, this.metadataBuildingContext.getObjectNameNormalizer());
if (schemaName != null) {
params.setProperty(PersistentIdentifierGenerator.SCHEMA, schemaName);
}
if (catalogName != null) {
params.setProperty(PersistentIdentifierGenerator.CATALOG, catalogName);
}
id.setIdentifierGeneratorProperties(params);
// bind value
bindSimpleValue(identifier, null, id, EMPTY_PATH, mappings, sessionFactoryBeanName);
// create property
Property prop = new Property();
prop.setValue(id);
// bind property
bindProperty(identifier, prop, mappings);
// set identifier property
entity.setIdentifierProperty(prop);
id.getTable().setIdentifierValue(id);
}
private static void makeIdentifier(Element node, SimpleValue model, Mappings mappings) {
// GENERATOR
Element subnode = node.element( "generator" );
if ( subnode != null ) {
model.setIdentifierGeneratorStrategy( subnode.attributeValue( "class" ) );
Properties params = new Properties();
if ( mappings.getSchemaName() != null ) {
params.setProperty( PersistentIdentifierGenerator.SCHEMA, mappings.getSchemaName() );
}
if ( mappings.getCatalogName() != null ) {
params.setProperty( PersistentIdentifierGenerator.CATALOG, mappings.getCatalogName() );
}
Iterator iter = subnode.elementIterator( "param" );
while ( iter.hasNext() ) {
Element childNode = (Element) iter.next();
params.setProperty( childNode.attributeValue( "name" ), childNode.getText() );
}
model.setIdentifierGeneratorProperties( params );
}
model.getTable().setIdentifierValue( model );
// ID UNSAVED-VALUE
Attribute nullValueNode = node.attribute( "unsaved-value" );
if ( nullValueNode != null ) {
model.setNullValue( nullValueNode.getValue() );
}
else {
if ( "assigned".equals( model.getIdentifierGeneratorStrategy() ) ) {
model.setNullValue( "undefined" );
}
else {
model.setNullValue( null );
}
}
}
public IdentifierGenerator createIdentifierGenerator(
Dialect dialect,
String defaultCatalog,
String defaultSchema,
RootClass rootClass)
throws MappingException {
Properties params = new Properties();
//if the hibernate-mapping did not specify a schema/catalog, use the defaults
//specified by properties - but note that if the schema/catalog were specified
//in hibernate-mapping, or as params, they will already be initialized and
//will override the values set here (they are in identifierGeneratorProperties)
if ( defaultSchema!=null ) {
params.setProperty(PersistentIdentifierGenerator.SCHEMA, defaultSchema);
}
if ( defaultCatalog!=null ) {
params.setProperty(PersistentIdentifierGenerator.CATALOG, defaultCatalog);
}
//pass the entity-name, if not a collection-id
if (rootClass!=null) {
params.setProperty( IdentifierGenerator.ENTITY_NAME, rootClass.getEntityName() );
}
//init the table here instead of earlier, so that we can get a quoted table name
//TODO: would it be better to simply pass the qualified table name, instead of
// splitting it up into schema/catalog/table names
String tableName = getTable().getQuotedName(dialect);
params.setProperty( PersistentIdentifierGenerator.TABLE, tableName );
//pass the column name (a generated id almost always has a single column)
String columnName = ( (Column) getColumnIterator().next() ).getQuotedName(dialect);
params.setProperty( PersistentIdentifierGenerator.PK, columnName );
if (rootClass!=null) {
StringBuffer tables = new StringBuffer();
Iterator iter = rootClass.getIdentityTables().iterator();
while ( iter.hasNext() ) {
Table table= (Table) iter.next();
tables.append( table.getQuotedName(dialect) );
if ( iter.hasNext() ) tables.append(", ");
}
params.setProperty( PersistentIdentifierGenerator.TABLES, tables.toString() );
}
else {
params.setProperty( PersistentIdentifierGenerator.TABLES, tableName );
}
if (identifierGeneratorProperties!=null) {
params.putAll(identifierGeneratorProperties);
}
return IdentifierGeneratorFactory.create(
identifierGeneratorStrategy,
getType(),
params,
dialect
);
}