一对一,在对象模型里面就是一个对象持有对方的引用。在数据库里有三种方法。1、外键关联。2、主键关联。3、使用中间表。其中最常用的就是外键关联。
例如,husband和wife的对应关系。
Annotation方式:直接在字段上加上@OneToOne,可以使用@JoinColumn来指定外键字段的名称。
husband
1 @Entity
2 public class Husband {
3 private int id;
4 private String name;
5 private Wife wife;
6 @Id
7 @GeneratedValue
8 public int getId() {
9 return id;
10 }
11
12 public String getName() {
13 return name;
14 }
15 @OneToOne
16 @JoinColumn(name="wifeId")
17 public Wife getWife() {
18 return wife;
19 }
20 public void setId(int id) {
21 this.id = id;
22 }
23 public void setName(String name) {
24 this.name = name;
25 }
26 public void setWife(Wife wife) {
27 this.wife = wife;
28 }
29
30 }
2 public class Husband {
3 private int id;
4 private String name;
5 private Wife wife;
6 @Id
7 @GeneratedValue
8 public int getId() {
9 return id;
10 }
11
12 public String getName() {
13 return name;
14 }
15 @OneToOne
16 @JoinColumn(name="wifeId")
17 public Wife getWife() {
18 return wife;
19 }
20 public void setId(int id) {
21 this.id = id;
22 }
23 public void setName(String name) {
24 this.name = name;
25 }
26 public void setWife(Wife wife) {
27 this.wife = wife;
28 }
29
30 }
Xml方式:使用many-to-one标签并设置unique="true"。
<many-to-one name="wife" column="wife_id" unique="true"></many-to-one>