在我们项目使用中采用中间表最多的一般就是多对一,或者是多对多,当然一对一使用中间表也是可以的,但是这种几率通常少之又少!所以这里重点介绍多对一和一对多的采用中间表进行关联映射!
依然采用Group和Person来描述这个逻辑!
Annotations配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@Entity
@Table
(name=
"t_group"
)
publicclass Group {
private
Integer id;
private
String name;
@Id
@GeneratedValue
public
Integer getId() {
returnid;
}
publicvoid setId(Integer id) {
this
.id = id;
}
@Column
(name=
"g_name"
)
public
String getName() {
returnname;
}
publicvoid setName(String name) {
this
.name = name;
}
}
|
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
|
@Entity
@Table
(name=
"p_person"
)
publicclass Person {
private
Integer id;
private
String name;
private
Integer age;
private
Group group;
@ManyToOne
@JoinTable
(name=
"g_p"
,joinColumns={
@JoinColumn
(name=
"p_id"
)},
inverseJoinColumns={
@JoinColumn
(name=
"g_id"
)})
public
Group getGroup() {
returngroup;
}
publicvoid setGroup(Group group) {
this
.group = group;
}
@Id
@GeneratedValue
public
Integer getId() {
returnid;
}
publicvoid setId(Integer id) {
this
.id = id;
}
@Column
(name=
"p_name"
)
public
String getName() {
returnname;
}
publicvoid setName(String name) {
this
.name = name;
}
@Column
(name=
"p_age"
)
public
Integer getAge() {
returnage;
}
publicvoid setAge(Integer age) {
this
.age = age;
}
}
|
XML配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<?
xml
version
=
"1.0"
?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/HibernateMapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<
hibernate-mapping
package
=
"csg.hibernate.entity"
>
<
class
name
=
"Person"
table
=
"t_person"
>
<
id
name
=
"id"
>
<
column
name
=
"id"
/>
<
generator
class
=
"native"
/>
</
id
>
<
property
name
=
"name"
/>
<
property
name
=
"age"
/>
<
join
table
=
"t_p"
optional
=
"true"
>
<
key
column
=
"p_id"
></
key
>
<
many-to-one
name
=
"group"
column
=
"g_id"
class
=
"Group"
unique
=
"true"
/>
</
join
>
</
class
>
</
hibernate-mapping
>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?
xml
version
=
"1.0"
?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/HibernateMapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<
hibernate-mapping
package
=
"csg.hibernate.entity"
>
<
class
name
=
"Group"
table
=
"t_group"
>
<
id
name
=
"id"
>
<
column
name
=
"id"
/>
<
generator
class
=
"native"
/>
</
id
>
<
property
name
=
"name"
/>
</
class
>
</
hibernate-mapping
>
|
写这篇文章,我特意查询了一下网上的文章,发现大家都是采用XML配置的,所以我这里也写了Annotations配置,因为JPA中的Annotations使用起来远比XML要方便!OK?
本文转自 小夜的传说 51CTO博客,原文链接:http://blog.51cto.com/1936625305/1568948,如需转载请自行联系原作者