@Target({METHOD,FIELD}) @Retention(RUNTIME) public @interface GeneratedValue{ GenerationType strategy() default AUTO; String generator() default ""; }其中GenerationType:
public enum GenerationType{ TABLE, SEQUENCE, IDENTITY, AUTO }
1、TABLE
@Id @GeneratedValue(strategy = GenerationType.TABLE, generator="payablemoney_gen") @TableGenerator(name = "pk_gen", table="tb_generator", pkColumnName="gen_name", valueColumnName="gen_value", pkColumnValue="PAYABLEMOENY_PK", allocationSize=1 )
这里应用表tb_generator,定义为
CREATE TABLE tb_generator ( id NUMBER NOT NULL, gen_name VARCHAR2(255) NOT NULL, gen_value NUMBER NOT NULL, PRIMARY KEY(id) )
插入纪录,供生成主键使用
INSERT INTO tb_generator(id, gen_name, gen_value) VALUES (1,PAYABLEMOENY_PK', 1);在主键生成后,这条纪录的value值,按allocationSize递增。
@TableGenerator的定义:
@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME) public @interface TableGenerator { String name(); String table() default ""; String catalog() default ""; String schema() default ""; String pkColumnName() default ""; String valueColumnName() default ""; String pkColumnValue() default ""; int initialValue() default 0; int allocationSize() default 50; UniqueConstraint[] uniqueConstraints() default {}; }
2、SEQUENCE
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE,generator="payablemoney_seq") @SequenceGenerator(name="payablemoney_seq", sequenceName="seq_payment")
@SequenceGenerator定义
@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME) public @interface SequenceGenerator { String name(); String sequenceName() default ""; int initialValue() default 0; int allocationSize() default 50; }name属性表示该表主键生成策略的名称,它被引用在@GeneratedValue中设置的“generator”值中。
3、IDENTITY
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)4、AUTO
@Id @GeneratedValue(strategy = GenerationType.AUTO)
在指定主键时,如果不指定主键生成策略,默认为AUTO。
@Id跟下面的定义是一样的。
@Id @GeneratedValue(strategy = GenerationType.AUTO)二、hibernate主键策略生成器
public interface IdentifierGenerator { /** * The configuration parameter holding the entity name */ public static final String ENTITY_NAME = "entity_name"; /** * Generate a new identifier. * @param session * @param object the entity or toplevel collection for which the id is being generated * * @return a new identifier * @throws HibernateException */ public Serializable generate(SessionImplementor session, Object object) throws HibernateException; }
比如说,JPA标准用法
@Id @GeneratedValue(GenerationType.AUTO)就可以用hibernate特有以下用法来实现
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "assigned")
@GenericGenerator的定义:
@Target({PACKAGE, TYPE, METHOD, FIELD}) @Retention(RUNTIME) public @interface GenericGenerator { /** * unique generator name */ String name(); /** * Generator strategy either a predefined Hibernate * strategy or a fully qualified class name. */ String strategy(); /** * Optional generator parameters */ Parameter[] parameters() default {}; }name属性指定生成器名称。
对于这些hibernate主键生成策略和各自的具体生成器之间的关系,在org.hibernate.id.IdentifierGeneratorFactory中指定了,
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
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "native")
2、uuid
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "uuid")
3、hilo
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "hilo")
4、assigned
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "assigned")
5、identity
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "identity")
6、select
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name="select", strategy="select", parameters = { @Parameter(name = "key", value = "idstoerung") })
7、sequence
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "identity")
8、seqhilo
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "seqhilo", parameters = { @Parameter(name = "max_lo", value = "5") })
9、increment
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "increment")
10、foreign
@GeneratedValue(generator = "idGenerator") @GenericGenerator(name = "idGenerator", strategy = "foreign", parameters = { @Parameter(name = "property", value = "employee") })
注意:直接使用@PrimaryKeyJoinColumn 报错(?)
@OneToOne(cascade = CascadeType.ALL) @PrimaryKeyJoinColumn
例如
@Entity public class Employee { @Id Integer id; @OneToOne @PrimaryKeyJoinColumn EmployeeInfo info; ... }
应该为
@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
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "guid")12、uuid.hex
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "uuid.hex")
13、sequence-identity
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "sequence-identity", parameters = { @Parameter(name = "sequence", value = "seq_payablemoney") })四、通过@GenericGenerator自定义主键生成策略
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。
@GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "AssignedSequenceGenerator", parameters = { @Parameter(name = "sequence", value = "seq_payablemoney") })
值得注意的是,定义的这种策略,非常不可控。正常情况下,不建议这么做