- hibernate的主键生成器:
generator元素:表示了一个主键生成器,它用来为持久化类实例生成唯一的标识 。
1.1 程序员自己控制:assigned
1.2 数据库控制: identity(标识列/自动增长) sequence
1.3 hibernate控制:increment uuid/uuid.hex
1.4 其它:native
student id int
worker id varchar
2. 主键生成器要求
2.1 assigned
数据类型不限、保存前必须赋值
2.2 identity(重点掌握)
数字,无需赋值
2.3 sequence(重点掌握)
数字,无需赋值, 默认使hibernate_sequence这个序列,
也可以通过sequence/sequence_name参数赋值
2.4 increment
数字,无需赋值
2.5 uuid/uuid.hex (是由容器自动生成的一个32位的字符串,.hex代表的是十六进制)
32位的字符串,无需赋值,
2.6 native(重点掌握)
等于identity+sequence
- 自定义主键生成器
3.1 *.hbm.xml指定主键生成器类
3.2 创建主键生成器类
实现org.hibernate.id.IdentifierGenerator接口即可,并还可以实现org.hibernate.id.Configurable接口来读取一些配置信息
PersistentIdentifierGenerator.TABLE
PersistentIdentifierGenerator.PK
assigned、native、自定义主键
报错Exception in thread “main” org.hibernate.HibernateException: isConnected is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext
T
r
a
n
s
a
c
t
i
o
n
P
r
o
t
e
c
t
i
o
n
W
r
a
p
p
e
r
.
i
n
v
o
k
e
(
T
h
r
e
a
d
L
o
c
a
l
S
e
s
s
i
o
n
C
o
n
t
e
x
t
.
j
a
v
a
:
351
)
a
t
c
o
m
.
s
u
n
.
p
r
o
x
y
.
TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:351) at com.sun.proxy.
TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:351)atcom.sun.proxy.Proxy23.isConnected(Unknown Source)
at com.zking.two.util.SessionFactoryUtil.main(SessionFactoryUtil.java:18)
没有提交事务
加上 session.beginTransaction();开启事务就好了
org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned beforeQuery calling save(): com.zking.two.entity.Student
这个主键是交给程序员控制