HHH-3512 : id generator short-naming

git-svn-id: https://svn.jboss.org/repos/hibernate/core/trunk@15365 1b8cb986-b30d-0410-93ca-fae66ebed9b2
This commit is contained in:
Steve Ebersole 2008-10-21 18:46:51 +00:00
parent 538982e8e6
commit 84c4579520
14 changed files with 354 additions and 51 deletions

View File

@ -108,6 +108,8 @@ import org.hibernate.event.ReplicateEventListener;
import org.hibernate.event.SaveOrUpdateEventListener;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.PersistentIdentifierGenerator;
import org.hibernate.id.factory.IdentifierGeneratorFactory;
import org.hibernate.id.factory.DefaultIdentifierGeneratorFactory;
import org.hibernate.impl.SessionFactoryImpl;
import org.hibernate.mapping.AuxiliaryDatabaseObject;
import org.hibernate.mapping.Collection;
@ -202,6 +204,8 @@ public class Configuration implements Serializable {
private transient Mapping mapping = buildMapping();
private DefaultIdentifierGeneratorFactory identifierGeneratorFactory;
protected Configuration(SettingsFactory settingsFactory) {
this.settingsFactory = settingsFactory;
reset();
@ -245,6 +249,8 @@ public class Configuration implements Serializable {
entityTuplizerFactory = new EntityTuplizerFactory();
// componentTuplizerFactory = new ComponentTuplizerFactory();
identifierGeneratorFactory = new DefaultIdentifierGeneratorFactory();
}
public EntityTuplizerFactory getEntityTuplizerFactory() {
@ -750,43 +756,37 @@ public class Configuration implements Serializable {
Iterator iter = classes.values().iterator();
while ( iter.hasNext() ) {
PersistentClass pc = (PersistentClass) iter.next();
PersistentClass pc = ( PersistentClass ) iter.next();
if ( !pc.isInherited() ) {
IdentifierGenerator ig = pc.getIdentifier()
.createIdentifierGenerator(
dialect,
defaultCatalog,
defaultSchema,
(RootClass) pc
);
IdentifierGenerator ig = pc.getIdentifier().createIdentifierGenerator(
getIdentifierGeneratorFactory(),
dialect,
defaultCatalog,
defaultSchema,
(RootClass) pc
);
if ( ig instanceof PersistentIdentifierGenerator ) {
generators.put( ( (PersistentIdentifierGenerator) ig ).generatorKey(), ig );
}
}
}
iter = collections.values().iterator();
while ( iter.hasNext() ) {
Collection collection = (Collection) iter.next();
Collection collection = ( Collection ) iter.next();
if ( collection.isIdentified() ) {
IdentifierGenerator ig = ( (IdentifierCollection) collection ).getIdentifier()
.createIdentifierGenerator(
dialect,
defaultCatalog,
defaultSchema,
null
);
IdentifierGenerator ig = ( ( IdentifierCollection ) collection ).getIdentifier().createIdentifierGenerator(
getIdentifierGeneratorFactory(),
dialect,
defaultCatalog,
defaultSchema,
null
);
if ( ig instanceof PersistentIdentifierGenerator ) {
generators.put( ( (PersistentIdentifierGenerator) ig ).generatorKey(), ig );
}
}
}
@ -2147,8 +2147,21 @@ public class Configuration implements Serializable {
return this;
}
/**
* Retrieve the IdentifierGeneratorFactory in effect for this configuration.
*
* @return This configuration's IdentifierGeneratorFactory.
*/
public DefaultIdentifierGeneratorFactory getIdentifierGeneratorFactory() {
return identifierGeneratorFactory;
}
public Mapping buildMapping() {
return new Mapping() {
public IdentifierGeneratorFactory getIdentifierGeneratorFactory() {
return identifierGeneratorFactory;
}
/**
* Returns the identifier type of a mapped class
*/
@ -2718,5 +2731,8 @@ public class Configuration implements Serializable {
extendsQueue.put( entry, null );
}
public DefaultIdentifierGeneratorFactory getIdentifierGeneratorFactory() {
return identifierGeneratorFactory;
}
}
}

View File

@ -162,6 +162,9 @@ public final class HbmBinder {
else if ( "fetch-profile".equals( elementName ) ) {
parseFetchProfile( element, mappings, null );
}
else if ( "identifier-generator".equals( elementName ) ) {
parseIdentifierGeneratorRegistration( element, mappings );
}
else if ( "typedef".equals( elementName ) ) {
bindTypeDef( element, mappings );
}
@ -200,6 +203,26 @@ public final class HbmBinder {
}
}
private static void parseIdentifierGeneratorRegistration(Element element, Mappings mappings) {
String strategy = element.attributeValue( "name" );
if ( StringHelper.isEmpty( strategy ) ) {
throw new MappingException( "'name' attribute expected for identifier-generator elements" );
}
String generatorClassName = element.attributeValue( "class" );
if ( StringHelper.isEmpty( generatorClassName ) ) {
throw new MappingException( "'class' attribute expected for identifier-generator [identifier-generator@name=" + strategy + "]" );
}
try {
Class generatorClass = ReflectHelper.classForName( generatorClassName );
mappings.getIdentifierGeneratorFactory().register( strategy, generatorClass );
}
catch ( ClassNotFoundException e ) {
throw new MappingException( "Unable to locate identifier-generator class [name=" + strategy + ", class=" + generatorClassName + "]" );
}
}
private static void bindImport(Element importNode, Mappings mappings) {
String className = getClassName( importNode.attribute( "class" ), mappings );
Attribute renameNode = importNode.attribute( "rename" );

View File

@ -32,6 +32,7 @@ import java.util.ListIterator;
import org.hibernate.DuplicateMappingException;
import org.hibernate.MappingException;
import org.hibernate.id.factory.DefaultIdentifierGeneratorFactory;
import org.hibernate.engine.FilterDefinition;
import org.hibernate.engine.NamedQueryDefinition;
import org.hibernate.engine.NamedSQLQueryDefinition;
@ -518,4 +519,11 @@ public interface Mappings {
* @param entry The entry to add.
*/
public void addToExtendsQueue(ExtendsQueueEntry entry);
/**
* Retrieve the IdentifierGeneratorFactory in effect for this mapping.
*
* @return The IdentifierGeneratorFactory
*/
public DefaultIdentifierGeneratorFactory getIdentifierGeneratorFactory();
}

View File

@ -25,6 +25,7 @@
package org.hibernate.engine;
import org.hibernate.MappingException;
import org.hibernate.id.factory.IdentifierGeneratorFactory;
import org.hibernate.type.Type;
/**
@ -38,6 +39,12 @@ import org.hibernate.type.Type;
* @author Gavin King
*/
public interface Mapping {
/**
* Allow access to the id generator factory, though this is only needed/allowed from configuration.
* @return
* @deprecated temporary solution
*/
public IdentifierGeneratorFactory getIdentifierGeneratorFactory();
public Type getIdentifierType(String className) throws MappingException;
public String getIdentifierPropertyName(String className) throws MappingException;
public Type getReferencedPropertyType(String className, String propertyName) throws MappingException;

View File

@ -0,0 +1,139 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.id.factory;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.UUIDHexGenerator;
import org.hibernate.id.TableHiLoGenerator;
import org.hibernate.id.Assigned;
import org.hibernate.id.IdentityGenerator;
import org.hibernate.id.SelectGenerator;
import org.hibernate.id.SequenceGenerator;
import org.hibernate.id.SequenceHiLoGenerator;
import org.hibernate.id.IncrementGenerator;
import org.hibernate.id.ForeignGenerator;
import org.hibernate.id.GUIDGenerator;
import org.hibernate.id.SequenceIdentityGenerator;
import org.hibernate.id.Configurable;
import org.hibernate.id.enhanced.SequenceStyleGenerator;
import org.hibernate.id.enhanced.TableGenerator;
import org.hibernate.type.Type;
import org.hibernate.util.FastHashMap;
import org.hibernate.util.ReflectHelper;
import org.hibernate.dialect.Dialect;
import org.hibernate.MappingException;
/**
* Basic <tt>templated</tt> support for {@link IdentifierGeneratorFactory} implementations.
*
* @author Steve Ebersole
*/
public class DefaultIdentifierGeneratorFactory implements IdentifierGeneratorFactory {
private static final Logger log = LoggerFactory.getLogger( DefaultIdentifierGeneratorFactory.class );
private Dialect dialect;
private FastHashMap generatorStrategyToClassNameMap = new FastHashMap();
/**
* Constructs a new DefaultIdentifierGeneratorFactory.
*/
public DefaultIdentifierGeneratorFactory() {
register( "uuid", UUIDHexGenerator.class );
register( "hilo", TableHiLoGenerator.class );
register( "assigned", Assigned.class );
register( "identity", IdentityGenerator.class );
register( "select", SelectGenerator.class );
register( "sequence", SequenceGenerator.class );
register( "seqhilo", SequenceHiLoGenerator.class );
register( "increment", IncrementGenerator.class );
register( "foreign", ForeignGenerator.class );
register( "guid", GUIDGenerator.class );
register( "uuid.hex", UUIDHexGenerator.class ); // uuid.hex is deprecated
register( "sequence-identity", SequenceIdentityGenerator.class );
register( "enhanced-sequence", SequenceStyleGenerator.class );
register( "enhanced-table", TableGenerator.class );
}
/**
* {@inheritDoc}
*/
public void setDialect(Dialect dialect) {
log.debug( "Setting dialect [" + dialect + "]" );
this.dialect = dialect;
}
public void register(String strategy, Class generatorClass) {
String msg = "Registering IdentifierGenerator strategy [" + strategy + "] -> [" + generatorClass + "]";
Object old = generatorStrategyToClassNameMap.put( strategy, generatorClass );
if ( old != null ) {
msg += ", overriding [" + old + "]";
}
log.debug( msg );
}
/**
* {@inheritDoc}
*/
public IdentifierGenerator createIdentifierGenerator(String strategy, Type type, Properties config) {
try {
Class clazz = getIdentifierGeneratorClass( strategy );
IdentifierGenerator idgen = ( IdentifierGenerator ) clazz.newInstance();
if ( idgen instanceof Configurable ) {
( ( Configurable ) idgen ).configure( type, config, dialect );
}
return idgen;
}
catch ( Exception e ) {
String msg = "Could not instantiate id generator [entity-name="
+ config.get( IdentifierGenerator.ENTITY_NAME ) + "]";
throw new MappingException( msg, e );
}
}
/**
* {@inheritDoc}
*/
public Class getIdentifierGeneratorClass(String strategy) {
if ( "native".equals( strategy ) ) {
return dialect.getNativeIdentifierGeneratorClass();
}
Class generatorClass = ( Class ) generatorStrategyToClassNameMap.get( strategy );
try {
if ( generatorClass == null ) {
generatorClass = ReflectHelper.classForName( strategy );
}
}
catch ( ClassNotFoundException e ) {
throw new MappingException( "Could not interpret id generator strategy [" + strategy + "]" );
}
return generatorClass;
}
}

View File

@ -0,0 +1,90 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.id.factory;
import java.util.Properties;
import java.io.Serializable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.type.Type;
import org.hibernate.dialect.Dialect;
/**
* Contract for a <tt>factory</tt> of {@link IdentifierGenerator} instances.
*
* @author Steve Ebersole
*/
public interface IdentifierGeneratorFactory {
/**
* Marker object returned from {@link IdentifierGenerator#generate} to indicate that we should short-circuit any
* continued generated id checking. Currently this is only used in the case of the
* {@link org.hibernate.id.ForeignGenerator foreign} generator as a way to signal that we should use the associated
* entity's id value.
*/
public static final Serializable SHORT_CIRCUIT_INDICATOR = new Serializable() {
public String toString() {
return "SHORT_CIRCUIT_INDICATOR";
}
};
/**
* Marker object returned from {@link IdentifierGenerator#generate} to indicate that the entity's identifier will
* be generated as part of the datbase insertion.
*/
public static final Serializable POST_INSERT_INDICATOR = new Serializable() {
public String toString() {
return "POST_INSERT_INDICATOR";
}
};
/**
* Allow injection of the dialect to use.
*
* @param dialect The dialect
* @deprecated The intention is that Dialect should be required to be specified up-front and it would then get
* ctor injected.
*/
public void setDialect(Dialect dialect);
/**
* Given a strategy, retrieve the appropriate identifier generator instance.
*
* @param strategy The generation strategy.
* @param type The mapping type for the identifier values.
* @param config Any configuraion properties given in the generator mapping.
*
* @return The appropriate generator instance.
*/
public IdentifierGenerator createIdentifierGenerator(String strategy, Type type, Properties config);
/**
* Retrieve the class that will be used as the {@link IdentifierGenerator} for the given strategy.
*
* @param strategy The strategy
* @return The generator class.
*/
public Class getIdentifierGeneratorClass(String strategy);
}

View File

@ -96,6 +96,7 @@ import org.hibernate.event.EventListeners;
import org.hibernate.exception.SQLExceptionConverter;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.UUIDHexGenerator;
import org.hibernate.id.factory.IdentifierGeneratorFactory;
import org.hibernate.jdbc.BatcherFactory;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass;
@ -233,11 +234,12 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI
PersistentClass model = (PersistentClass) classes.next();
if ( !model.isInherited() ) {
IdentifierGenerator generator = model.getIdentifier().createIdentifierGenerator(
cfg.getIdentifierGeneratorFactory(),
settings.getDialect(),
settings.getDefaultCatalogName(),
settings.getDefaultSchemaName(),
(RootClass) model
);
);
identifierGenerators.put( model.getEntityName(), generator );
}
}
@ -467,6 +469,10 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI
this.observer.sessionFactoryCreated( this );
}
public IdentifierGeneratorFactory getIdentifierGeneratorFactory() {
return null;
}
private void registerEntityNameResolvers(EntityPersister persister) {
if ( persister.getEntityMetamodel() == null || persister.getEntityMetamodel().getTuplizerMapping() == null ) {
return;

View File

@ -27,6 +27,7 @@ package org.hibernate.mapping;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.factory.IdentifierGeneratorFactory;
/**
* Represents an identifying key of a table: the value for primary key
@ -35,20 +36,21 @@ import org.hibernate.id.IdentifierGenerator;
* @author Gavin King
*/
public interface KeyValue extends Value {
public IdentifierGenerator createIdentifierGenerator(
IdentifierGeneratorFactory identifierGeneratorFactory,
Dialect dialect,
String defaultCatalog,
String defaultSchema,
RootClass rootClass) throws MappingException;
public boolean isIdentityColumn(IdentifierGeneratorFactory identifierGeneratorFactory, Dialect dialect);
public void createForeignKeyOfEntity(String entityName);
public boolean isCascadeDeleteEnabled();
public boolean isIdentityColumn(Dialect dialect);
public String getNullValue();
public boolean isUpdateable();
public IdentifierGenerator createIdentifierGenerator(
Dialect dialect,
String defaultCatalog,
String defaultSchema,
RootClass rootClass) throws MappingException;
}

View File

@ -34,9 +34,9 @@ import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.Mapping;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.IdentifierGeneratorFactory;
import org.hibernate.id.IdentityGenerator;
import org.hibernate.id.PersistentIdentifierGenerator;
import org.hibernate.id.factory.IdentifierGeneratorFactory;
import org.hibernate.type.Type;
import org.hibernate.type.TypeFactory;
import org.hibernate.util.ReflectHelper;
@ -120,6 +120,7 @@ public class SimpleValue implements KeyValue {
}
public IdentifierGenerator createIdentifierGenerator(
IdentifierGeneratorFactory identifierGeneratorFactory,
Dialect dialect,
String defaultCatalog,
String defaultSchema,
@ -171,13 +172,9 @@ public class SimpleValue implements KeyValue {
if (identifierGeneratorProperties!=null) {
params.putAll(identifierGeneratorProperties);
}
return IdentifierGeneratorFactory.create(
identifierGeneratorStrategy,
getType(),
params,
dialect
);
identifierGeneratorFactory.setDialect( dialect );
return identifierGeneratorFactory.createIdentifierGenerator( identifierGeneratorStrategy, getType(), params );
}
@ -210,9 +207,10 @@ public class SimpleValue implements KeyValue {
return identifierGeneratorStrategy;
}
public boolean isIdentityColumn(Dialect dialect) {
return IdentifierGeneratorFactory.getIdentifierGeneratorClass(identifierGeneratorStrategy, dialect)
.equals(IdentityGenerator.class);
public boolean isIdentityColumn(IdentifierGeneratorFactory identifierGeneratorFactory, Dialect dialect) {
identifierGeneratorFactory.setDialect( dialect );
return identifierGeneratorFactory.getIdentifierGeneratorClass( identifierGeneratorStrategy )
.equals( IdentityGenerator.class );
}
/**

View File

@ -392,7 +392,7 @@ public class Table implements RelationalModel, Serializable {
.append( getQualifiedName( dialect, defaultCatalog, defaultSchema ) )
.append( " (" );
boolean identityColumn = idValue != null && idValue.isIdentityColumn( dialect );
boolean identityColumn = idValue != null && idValue.isIdentityColumn( p.getIdentifierGeneratorFactory(), dialect );
// Try to find out the name of the primary key to create it as identity if the IdentityGenerator is used
String pkname = null;

View File

@ -421,12 +421,13 @@ public abstract class AbstractCollectionPersister
identifierColumnName = col.getQuotedName(dialect);
identifierColumnAlias = col.getAlias(dialect);
//unquotedIdentifierColumnName = identifierColumnAlias;
identifierGenerator = idColl.getIdentifier().createIdentifierGenerator(
identifierGenerator = idColl.getIdentifier().createIdentifierGenerator(
cfg.getIdentifierGeneratorFactory(),
factory.getDialect(),
factory.getSettings().getDefaultCatalogName(),
factory.getSettings().getDefaultSchemaName(),
null
);
);
}
else {
identifierType = null;

View File

@ -17,8 +17,10 @@ arbitrary number of queries, and import declarations of arbitrary classes.
-->
<!ELEMENT hibernate-mapping (
meta*,
typedef*,
meta*,
identifier-generator*,
typedef*,
filter-def*,
import*,
(class|subclass|joined-subclass|union-subclass)*,
resultset*,
@ -36,7 +38,7 @@ arbitrary number of queries, and import declarations of arbitrary classes.
<!ATTLIST hibernate-mapping package CDATA #IMPLIED> <!-- default: none -->
<!--
META element definition; used to assign meta-level attributes to a class
<meta.../> is used to assign meta-level attributes to a class
or property. Is currently used by codegenerator as a placeholder for
values that is not directly related to OR mappings.
-->
@ -45,7 +47,14 @@ arbitrary number of queries, and import declarations of arbitrary classes.
<!ATTLIST meta inherit (true|false) "true">
<!--
TYPEDEF element definition; defines a new name for a Hibernate type. May
<identifier-generator.../> allows customized short-naming of IdentifierGenerator implementations.
-->
<!ELEMENT identifier-generator EMPTY>
<!ATTLIST identifier-generator name CDATA #REQUIRED>
<!ATTLIST identifier-generator class CDATA #REQUIRED>
<!--
<typedef.../> allows defining a customized type mapping for a Hibernate type. May
contain parameters for parameterizable types.
-->
<!ELEMENT typedef (param*)>

View File

@ -5,9 +5,11 @@
<hibernate-mapping package="org.hibernate.test.idgen.enhanced.table">
<identifier-generator name="table" class="org.hibernate.id.enhanced.TableGenerator"/>
<class name="Entity" table="ID_TBL_BSC_ENTITY">
<id name="id" column="ID" type="long">
<generator class="org.hibernate.id.enhanced.TableGenerator">
<generator class="table">
<param name="table_name">ID_TBL_BSC_TBL</param>
<param name="segment_value">test</param>
<param name="initial_value">1</param>

View File

@ -5,9 +5,11 @@
<hibernate-mapping package="org.hibernate.test.idgen.enhanced.table">
<identifier-generator name="table" class="org.hibernate.id.enhanced.TableGenerator"/>
<class name="Entity" table="ID_TBL_HILO_ENTITY">
<id name="id" column="ID" type="long">
<generator class="org.hibernate.id.enhanced.TableGenerator">
<generator class="table">
<param name="table_name">ID_TBL_HILO_TBL</param>
<param name="segment_value">test</param>
<param name="initial_value">1</param>