JPA Hibernate 使用UUID做为主键的问题


1.将数据库中的主键,设置为varchar(32)。

2.在entity中类头部写入@GenericGenerator(name = "jpa-uuid", strategy = "uuid")

3.在entity中id主键顶部写入@GeneratedValue(generator = "jpa-uuid"),注意generator中的值必须与注释@GenericGenerator中name属性完全一致。

4.设置entity中主键ID为string类型。设置长度为32

5.GenericGenerator是Hibernate中的注释,有两个参数。name是system-uuid“” ,策略strategy是uuid 。

6.@GenericGenerator支持13种策略,分别是:

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); } 
上面的12种策略,再加上native,一共是13种。
7.@GeneratedValue注解属于一个JPA接口(从JAVA EE 5开始,存在于javax.persistence包下),其接口下包含了两个抽象的参数,GenerationType类型的strategy和String类型的generator,并且两个参数都有相应的默认值。 

8.GenerationType同样也位于javax.persistence包下,并且还继承了Enum枚举类,然后其中有4个值供我们使用,分别是: 
TABLE:使用一个特定的数据库表格来保存主键。 
SEQUENCE:根据底层数据库的序列来生成主键,条件是数据库支持序列。 这个值要与generator一起使用,generator 指定生成主键使用的生成器(可能是orcale中自己编写的序列)。 
IDENTITY:主键由数据库自动生成(主要是支持自动增长的数据库,如mysql) 
AUTO:主键由程序控制,也是GenerationType的默认值。

9.两个数据库对GenerationType的支持

mysql 
GenerationType.TABLE 
GenerationType.AUTO 
GenerationType.IDENTITY 
不支持GenerationType.SEQUENCE

oracle 
strategy=GenerationType.AUTO 
GenerationType.SEQUENCE 
GenerationType.TABLE 
不支持GenerationType.IDENTITY


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM