public class GWgDyEntity implements Serializable { 2 3 //在主键上添加注释: 4 @Id 5 @GeneratedValue(strategy = GenerationType.AUTO) 6 @Column(name = "OBJECTID") 7 public long getObjectid() { 8 return objectid; 9 }
如果在Hibernate 5上运行相同的单元测试,您将获得以下SQL语句:
1个
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18岁
19
20
21
22
23
24
25
26
|
SELECT next_val as id_val
FROM hibernate_sequence FOR UPDATE
UPDATE hibernate_sequence
SET next_val= 2 where next_val=1
SELECT next_val as id_val
FROM hibernate_sequence FOR UPDATE
UPDATE hibernate_sequence
SET next_val= 3 where next_val=1
SELECT next_val as id_val
FROM hibernate_sequence FOR UPDATE
UPDATE hibernate_sequence
SET next_val= 4 where next_val=3
INSERT INTO post (title, id)
VALUES ( 'High-Performance Java Persistence, Part 1' , 1)
INSERT INTO post (title, id)
VALUES ( 'High-Performance Java Persistence, Part 2' , 2)
INSERT INTO post (title, id)
VALUES ( 'High-Performance Java Persistence, Part 3' , 3)
|
发生什么事了 好吧,当基础数据库不支持序列时,Hibernate选择TABLE
生成器,而不是选择生成器IDENTITY
。但是,TABLE
生成器不是一个好的选择。请查看HHH-11014 Jira问题,以获取与此行为更改相关的更多详细信息。
如何解决?
该修复程序非常简单。您只需要使用native
标识符即可:
1个
2
3
4
5
6
7
8
9
10
|
@Id
@GeneratedValue (
strategy= GenerationType.AUTO,
generator= "native"
)
@GenericGenerator (
name = "native" ,
strategy = "native"
)
private Long id;
|
现在,在运行先前的测试用例时,Hibernate改为使用IDENTITY列:
1个
2
3
4
5
6
7
8
|
INSERT INTO post (title)
VALUES ( 'High-Performance Java Persistence, Part 1' )
INSERT INTO post (title)
VALUES ( 'High-Performance Java Persistence, Part 2' )
INSERT INTO post (title)
VALUES ( 'High-Performance Java Persistence, Part 3' )
|
如果您想使用一种可移植的解决方案来管理自定义SEQUENCE
生成器,同时仍然允许您选择IDENTITY
MySQL 的生成器,那么请查看本文。
结论
JPA可移植性是一个神话!实际上,如果您需要高性能的企业应用程序,则必须了解底层JPA提供程序的详细信