支持的策略包括:uuid, hilo, assigned, identity, select, sequence, seqhilo, increment, foreign, guid, uuid.hex, sequence-identity.
对应这些策略, 可以在org.hibernate.id包下找到, 其中有一个IdentifierGeneratorFactory类用于根据实体类的配置(hbm文件的元素或@Id,@GeneratedValue注解)来创建相应的策略.
public final class IdentifierGeneratorFactory {
... //注册所有支持的ID生成策略
private static final HashMap GENERATORS = new HashMap();
static {
GENERATORS.put( "uuid", UUIDHexGenerator.class );
GENERATORS.put( "hilo", TableHiLoGenerator.class );
GENERATORS.put( "assigned", Assigned.class );
GENERATORS.put( "identity", IdentityGenerator.class );
GENERATORS.put( "select", SelectGenerator.class );
GENERATORS.put( "sequence", SequenceGenerator.class );
GENERATORS.put( "seqhilo", SequenceHiLoGenerator.class );
GENERATORS.put( "increment", IncrementGenerator.class );
GENERATORS.put( "foreign", ForeignGenerator.class );
GENERATORS.put( "guid", GUIDGenerator.class );
GENERATORS.put( "uuid.hex", UUIDHexGenerator.class ); // uuid.hex is deprecated
GENERATORS.put( "sequence-identity", SequenceIdentityGenerator.class );
}
...
public static IdentifierGenerator create(String strategy, Type type, Properties params, Dialect dialect)
throws MappingException {
try {
Class clazz = getIdentifierGeneratorClass( strategy, dialect );
...
}
public static Class getIdentifierGeneratorClass(String strategy, Dialect dialect) {
Class clazz = ( Class ) GENERATORS.get( strategy );
...
}
}
显然create()方法是用于创建ID生成器的, 而且用到了参数strategy和dialect. Hibernate在初始化SessionFactory的时候就会准备这些ID生成器. 见以下代码
SessionFactoryImpl(){
...
Iterator classes = cfg.getClassMappings();
while ( classes.hasNext() ) {
Persist