欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

基于按annotation的hibernate主键生成策略[转载]

程序员文章站 2022-07-15 14:54:11
...
自定义主键生成策略,由@GenericGenerator实现。  
hibernate在JPA的基础上进行了扩展,可以用一下方式引入hibernate独有的主键生成策略,就是通过@GenericGenerator加入的。  
 
比如说,JPA标准用法  
Java代码  
@Id    
@GeneratedValue(GenerationType.AUTO)    
 
就可以用hibernate特有以下用法来实现  
Java代码  
@GeneratedValue(generator = "paymentableGenerator")       
@GenericGenerator(name = "paymentableGenerator", strategy = "assigned")    
 
 
@GenericGenerator的定义:  
Java代码  
@Target({PACKAGE, TYPE, METHOD, FIELD})     
@Retention(RUNTIME)     
public @interface GenericGenerator {     
    
String name();     
    
String strategy();     
    
Parameter[] parameters() default {};     
}    
 
 
name属性指定生成器名称。  
strategy属性指定具体生成器的类名。  
parameters得到strategy指定的具体生成器所用到的参数。  
 
对于这些hibernate主键生成策略和各自的具体生成器之间的关系,在org.hibernate.id.IdentifierGeneratorFactory中指定了,  
Java代码  
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);     
}    
 
上面十二种策略,加上native,hibernate一共默认支持十三种生成策略。  
 
1、native 对于orcale采用Sequence方式,对于MySQL和SQL Server采用identity(处境主键生成机制),native就是将主键的生成工作交给数据库本身,hibernate不管。(很常用)  
Java代码  
@GeneratedValue(generator = "paymentableGenerator")       
@GenericGenerator(name = "paymentableGenerator", strategy = "native")     
 
2、uuid  采用128位的uuid算法生成主键,uuid被编码为一个32位16进制数字的字符串。占用空间大(字符串类型)。  
Java代码  
@GeneratedValue(generator = "paymentableGenerator")       
@GenericGenerator(name = "paymentableGenerator", strategy = "uuid")     
 
3、hilo 要在数据库中建立一张额外的表,默认表名为hibernate_unque_key,默认字段为integer类型,名称是next_hi(比较少用)  
Java代码  
@GeneratedValue(generator = "paymentableGenerator")       
@GenericGenerator(name = "paymentableGenerator", strategy = "hilo")     
 
4、assigned 在插入数据的时候主键由程序处理(很常用),这是<generator>元素没有指定时的默认生成策略。等同于JPA中的AUTO。  
Java代码  
@GeneratedValue(generator = "paymentableGenerator")       
@GenericGenerator(name = "paymentableGenerator", strategy = "assigned")     
 
5、identity 使用SQL Server和MySQL的自增字段,这个方法不能放到Oracle中,Oracle不支持自增字段,要设定sequence(MySQL和SQL Server中很常用)。等同于JPA中的IDENTITY  
Java代码  
@GeneratedValue(generator = "paymentableGenerator")       
@GenericGenerator(name = "paymentableGenerator", strategy = "identity")     
 
6、select 使用触发器生成主键(主要用于早期的数据库主键生成机制,少用)  
Java代码  
@GeneratedValue(generator = "paymentableGenerator")     
@GenericGenerator(name="select", strategy="select",     
      parameters = { @Parameter(name = "key", value = "idstoerung") })    
 
7、sequence 调用谨慎数据库的序列来生成主键,要设定序列名,不然hibernate无法找到。  
Java代码  
@GeneratedValue(generator = "paymentableGenerator")     
@GenericGenerator(name = "paymentableGenerator", strategy = "sequence",     
          parameters = { @Parameter(name = "sequence", value = "seq_payablemoney") })    
 
8、seqhilo 通过hilo算法实现,但是主键历史保存在Sequence中,适用于支持Sequence的数据库,如Orcale(比较少用)  
Java代码  
@GeneratedValue(generator = "paymentableGenerator")     
@GenericGenerator(name = "paymentableGenerator", strategy = "seqhilo",     
          parameters = { @Parameter(name = "max_lo", value = "5") })    
 
9、increment 插入数据的时候hibernate会给主键添加一个自增的主键,但是一个hibernate实例就维护一个计数器,所以在多个实例运行的时候不能使用这个方法。  
Java代码  
@GeneratedValue(generator = "paymentableGenerator")       
@GenericGenerator(name = "paymentableGenerator", strategy = "increment")     
 
10、foreign  
Java代码  
@GeneratedValue(generator = "idGenerator")     
@GenericGenerator(name = "idGenerator", strategy = "foreign",     
          parameters = { @Parameter(name = "property", value = "employee") })    
 
 
注意:直接使用@PrimaryKeyJoinColumn 报错(?)  
Java代码  
@OneToOne(cascade = CascadeType.ALL)     
@PrimaryKeyJoinColumn     
例如  
Java代码  
@Entity    
public class Employee {     
  @Id Integer id;     
         
  @OneToOne @PrimaryKeyJoinColumn    
   EmployeeInfo info;     
        
}    
应该为  
Java代码  
@Entity    
public class Employee {     
  @Id     
  @GeneratedValue(generator = "idGenerator")     
  @GenericGenerator(name = "idGenerator", strategy = "foreign",     
          parameters = { @Parameter(name = "property", value = "info") })     
   Integer id;     
         
  @OneToOne    
   EmployeeInfo info;     
        
}    
11、guid 采用数据库底层的guid算法机制,对应MySQL的uuid()函数,SQL Server的newid()函数,ORCALE的rawtohex(sys_guid())函数等  
Java代码  
@GeneratedValue(generator = "paymentableGenerator")       
@GenericGenerator(name = "paymentableGenerator", strategy = "guid")     
 
12、uuid.hex 看uudi,建议用uuid替换  
Java代码  
@GeneratedValue(generator = "paymentableGenerator")       
@GenericGenerator(name = "paymentableGenerator", strategy = "uuid.hex")     
 
13、sequence-identity  
Java代码  
@GeneratedValue(generator = "paymentableGenerator")     
@GenericGenerator(name = "paymentableGenerator", strategy = "sequence-identity",     
          parameters = { @Parameter(name = "sequence", value = "seq_payablemoney") })    
 
四、通过@GenericGenerator自定义主键生成策略  
如果实际应用中,主键策略为程序指定了就用程序指定的主键(assigned),没有指定就从sequence中取。  
明显上面所讨论的策略都不满足,只好自己扩展了,集成assigned和sequence两种策略。  
 
Java代码  
public class AssignedSequenceGenerator extends SequenceGenerator implements     
PersistentIdentifierGenerator, Configurable {     
private String entityName;     
       
public void configure(Type type, Properties params, Dialect dialect) throws MappingException {     
   entityName = params.getProperty(ENTITY_NAME);     
  if (entityName==null) {     
   throw new MappingException("no entity name");     
   }     
       
  super.configure(type, params, dialect);       
}     
    
public Serializable generate(SessionImplementor session, Object obj)     
  throws HibernateException {     
       
   Serializable id = session.getEntityPersister( entityName, obj )     
     .getIdentifier( obj, session.getEntityMode() );     
       
  if (id==null) {     
    id = super.generate(session, obj);     
   }     
       
  return id;     
}     
}    
 
实际应用中,定义同sequence。  
Java代码  
@GeneratedValue(generator = "paymentableGenerator")     
@GenericGenerator(name = "paymentableGenerator", strategy = "AssignedSequenceGenerator",     
      parameters = { @Parameter(name = "sequence", value = "seq_payablemoney") })    
 
 
值得注意的是,定义的这种策略,就像打开了潘多拉魔盒,非常不可控。正常情况下,不建议这么做。  (??????有待试验)