和基于配置的一对一双向关联大体一致,修改实体类,添加注解,更改hibernate.cfg.xml,引入实体类
只列出实体类的变动
Card
1 package domain;
2
3 import javax.persistence.Entity;
4 import javax.persistence.GeneratedValue;
5 import javax.persistence.Id;
6 import javax.persistence.JoinColumn;
7 import javax.persistence.OneToOne;
8 import javax.persistence.Table;
9
10 @Entity
11 @Table(name="t_card")
12 public class Card {
13
14 private int id;
15 private String no;
16 private Person person;
17
18 public Card() {
19 super();
20 }
21
22 public Card(int id, String no, Person person) {
23 super();
24 this.id = id;
25 this.no = no;
26 this.person = person;
27 }
28
29 @Id
30 @GeneratedValue
31 public int getId() {
32 return id;
33 }
34 public void setId(int id) {
35 this.id = id;
36 }
37 public String getNo() {
38 return no;
39 }
40 public void setNo(String no) {
41 this.no = no;
42 }
43 @OneToOne
44 @JoinColumn(name="pid")
45 //设置外键名称
46 public Person getPerson() {
47 return person;
48 }
49 public void setPerson(Person person) {
50 this.person = person;
51 }
52
53 }
54
Person
1 package domain;
2
3 import javax.persistence.Entity;
4 import javax.persistence.GeneratedValue;
5 import javax.persistence.Id;
6 import javax.persistence.OneToOne;
7 import javax.persistence.Table;
8
9 @Entity
10 @Table(name="t_person")
11 public class Person {
12
13 private int id;
14 private String name;
15 private Card card;
16
17 public Person() {
18 super();
19 }
20
21 public Person(int id, String name, Card card) {
22 super();
23 this.id = id;
24 this.name = name;
25 this.card = card;
26 }
27
28 @Id
29 @GeneratedValue
30 public int getId() {
31 return id;
32 }
33 public void setId(int id) {
34 this.id = id;
35 }
36 public String getName() {
37 return name;
38 }
39 public void setName(String name) {
40 this.name = name;
41 }
42 @OneToOne(mappedBy="person")
43 //关系控制交由对方
44 public Card getCard() {
45 return card;
46 }
47 public void setCard(Card card) {
48 this.card = card;
49 }
50
51 }
52