JPA基础(十一):JPA中的一对一双向关联

Person.java:

 1 @Entity
2 public class Person {
3 @Id
4 @GeneratedValue
5 private Integer id;
6 @Column(length=10,nullable=false)
7 private String name;
8 @OneToOne(cascade=CascadeType.ALL,optional=false)
9 @JoinColumn(name="idcard_id")
10 private IDCard idcard;
11 public Person(){};
12 public Person(String name) {
13 super();
14 this.name = name;
15 }
16 public IDCard getIdcard() {
17 return idcard;
18 }
19 public void setIdcard(IDCard idcard) {
20 this.idcard = idcard;
21 }
22 public Integer getId() {
23 return id;
24 }
25 public void setId(Integer id) {
26 this.id = id;
27 }
28 public String getName() {
29 return name;
30 }
31 public void setName(String name) {
32 this.name = name;
33 }
34
35 }

IDCard.java:

 1 @Entity
2 public class IDCard {
3 @Id
4 @GeneratedValue
5 private Integer id;
6 @Column(length=18,nullable=false)
7 private String cardno;
8 @OneToOne(mappedBy="idcard",cascade={CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REFRESH})
9 private Person person;
10 public IDCard(){};
11 public IDCard(String cardno) {
12 super();
13 this.cardno = cardno;
14 }
15 public Person getPerson() {
16 return person;
17 }
18 public void setPerson(Person person) {
19 this.person = person;
20 }
21 public Integer getId() {
22 return id;
23 }
24 public void setId(Integer id) {
25 this.id = id;
26 }
27 public String getCardno() {
28 return cardno;
29 }
30 public void setCardno(String cardno) {
31 this.cardno = cardno;
32 }
33
34 }

级联的定义,一定是根据你们的业务需求来定的。用不用是根据你的业务来决定的,业务需要就用,业务不需要就不用。

测试:

 1     @Test
2 public void save(){
3 EntityManagerFactory factory=Persistence.createEntityManagerFactory("sample");
4 EntityManager em=factory.createEntityManager();
5 em.getTransaction().begin();
6 Person person=new Person("jim");
7 person.setIdcard(new IDCard("123456789"));
8 em.persist(person);
9 em.getTransaction().commit();
10 em.close();
11 factory.close();
12 }


谁是关系维护端,谁就负责外键字段的更新。Person是关系维护端,IDCard是关系被维护端,怎么维护更新呢?往Person里面设置idCard,这样就相当于把关系建立起来了;如果通过IDCard设置person的话,那么这种关系是建立不起来的,因为IDCard是关系被维
护端。



你可能感兴趣的:(jpa)