基于中间表实现的一对多的关联映射,还是比较常见的。
Person(人)和Group(组)
Annotations配置
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
|
@Entity
@Table
(name=
"t_group"
)
publicclass Group {
private
Integer id;
private
String name;
private
Set<Person> persons=newHashSet<Person>();
@OneToMany
@JoinTable
(name=
"t_p"
,joinColumns={
@JoinColumn
(name=
"g_id"
)},
inverseJoinColumns={
@JoinColumn
(name=
"p_id"
)})
public
Set<Person> getPersons() {
returnpersons;
}
publicvoid setPersons(Set<Person> persons) {
this
.persons = persons;
}
@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
|
@Entity
@Table
(name=
"p_person"
)
publicclass Person {
private
Integer id;
private
String name;
private
Integer age;
@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
|
<?
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"
/>
<
set
name
=
"persons"
table
=
"t_p"
>
<
key
column
=
"g_id"
/>
<
many-to-many
column
=
"p_id"
class
=
"Person"
unique
=
"true"
/>
</
set
>
</
class
>
</
hibernate-mapping
>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?
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"
/>
</
class
>
</
hibernate-mapping
>
|
在一对多的中间表映射中,Hibernate自动会转化为多对多来处理!
本文转自 小夜的传说 51CTO博客,原文链接:http://blog.51cto.com/1936625305/1569047,如需转载请自行联系原作者