hibernate大家想必已经很熟悉,现在的注解太流行了,我就说下注解的作用。
下面是User类:
@onetomany
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
|
@Entity
@Table
(name=
"user"
)
public
class
User
implements
Serializable{
private
static
final
long
serialVersionUID = 6177417450707400228L;
@Id
@GeneratedValue
(strategy = GenerationType.AUTO)
@Column
(name=
"id"
)
private
int
id;
@Column
(name=
"name"
)
private
String name;
@Column
(name=
"password"
)
private
String password;
/*
* cascade:为级联操作,里面有级联保存,级联删除等,all为所有
* fetch:加载类型,有lazy和eager二种,
* eager为急加载,意为立即加载,在类加载时就加载,lazy为慢加载,第一次调用的时候再加载,由于数据量太大,onetomany一般为lazy
* mappedBy:这个为manytoone中的对象名,这个不要变哦
* Set<role>:这个类型有两种,一种为list另一种为set
*
*
*/
@OneToMany
(cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy=
"user"
)
private
Set<role> setRole;
public
int
getId() {
return
id;
}
public
void
setId(
int
id) {
this
.id = id;
}
public
String getName() {
return
name;
}
public
void
setName(String name) {
this
.name = name;
}
public
String getPassword() {
return
password;
}
public
void
setPassword(String password) {
this
.password = password;
}
public
Set<role> getSetRole() {
return
setRole;
}
public
void
setSetRole(Set<role> setRole) {
this
.setRole = setRole;
}
}
</role></role></role></role>
|
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
|
@Entity
@Table
(name=
"role"
)
public
class
Role {
private
static
final
long
serialVersionUID = 6177417450707400228L;
@Id
@GeneratedValue
(strategy = GenerationType.AUTO)
@Column
(name=
"role_id"
)
private
int
role_id;
@Column
(name=
"role_name"
)
private
String role_name;
@ManyToOne
(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
@JoinColumn
(name=
"user_id"
)
//加入一列作为外键
private
User user;
public
int
getRole_id() {
return
role_id;
}
public
void
setRole_id(
int
role_id) {
this
.role_id = role_id;
}
public
String getRole_name() {
return
role_name;
}
public
void
setRole_name(String role_name) {
this
.role_name = role_name;
}
public
User getUser() {
return
user;
}
public
void
setUser(User user) {
this
.user = user;
}
}
|
其中@table为映射表名,@column为映射列名,其他的我不一一细说了。
下面就是操作了,定义了级联操作,下面是保存的。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public
Role save() {
User user=
new
User();
user.setName(
"123456"
);
user.setPassword(
"123456"
);
Role role=
new
Role();
role.setRole_name(
"student"
);
role.setUser(user);
Role roler=registerDao.save(role);
return
roler;
}
|