10-主键的生成器 hibernate是根据映射文件的主键生成器生成主键哒,自己设置的主键不起作用 <!-- 主键的产生器,就该告诉hibernate容器用什么样的方式产生主键--> <generator class="increment"></generator> 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
| import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
public class GeneratorTest extends ConfigUtil{
/**
* Hibernate: select max(pid) from Person
Hibernate: insert into Person (pname, psex, pid) values (?, ?, ?)
说明:
1、主键的类型必须是数字
2、主键的生成是由hibernate内部完成的,程序员不需要干预
3、这种生成机制效率比较低
*/
@Test
public void testIncrement(){
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Person person = new Person();
person.setPname("班长3");
person.setPsex("女");
/**save的参数必须持久化对象*/
session.save(person);
transaction.commit();
session.close();
}
/*
* Hibernate: insert into Person (pname, psex) values (?, ?)
* 说明
* 1、新的主键的产生是由数据库完成的,并不是由hibernate或者程序员完成的
* 2、该表必须支持自动增长机制
* 3、效率比较高
*/
@Test
public void testIdentity(){
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Person person = new Person();
person.setPname("班长");
person.setPsex("女");
/**
* 参数必须持久化对象
*/
session.save(person);
transaction.commit();
session.close();
}
/**
* 由程序员手写设置主键
*/
@Test
public void testAssigned(){
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Person person = new Person();
person.setPid(4L);
person.setPname("班长");
person.setPsex("女");
session.save(person);
transaction.commit();
session.close();
}
/**
* 1、UUID是由hibernate内部生成的,主键的类型是String
* 2、主键的类型必须是字符串
*/
@Test
public void testUUID(){
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Person person = new Person();
person.setPname("班长");
person.setPsex("女");
session.save(person);
transaction.commit();
session.close();
}
/**
* hibernate内部是根据主键生成器来生成主键的,在客户端设置主键不一定起作用,在assigned的时候起作用
*/
@Test
public void testIdentity_ID(){
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Person person = new Person();
person.setPid(1L);
person.setPname("aa");
person.setPsex("aa");
session.save(person);
transaction.commit();
session.close();
}
}
|
|