JPA---一对一关系

时间:2022-10-11 23:13:55

在JPA中,使用@oneToOne来标示。

package com.yl.demo1.bean.oneToone;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne; @Entity
public class User {
private Integer id;
private String name;
private IDCard idcard; public User(){} public User(String name) {
super();
this.name = name;
}
@Id @GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length=10, nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToOne(optional=false, cascade=CascadeType.ALL)
@JoinColumn(name="idcard_id")
public IDCard getIdcard() {
return idcard;
}
public void setIdcard(IDCard idcard) {
this.idcard = idcard;
} }
 package com.yl.demo1.bean.oneToone;

 import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne; @Entity
public class IDCard {
private Integer id;
private String cardno;
private User user; public IDCard(){} public IDCard(String cardno) {
super();
this.cardno = cardno;
}
@Id @GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length=18, nullable=false)
public String getCardno() {
return cardno;
}
public void setCardno(String cardno) {
this.cardno = cardno;
}
/**
* 在一对一的关系中,出现mappedBy的对象为关系的被维护端
*
*/
@OneToOne(mappedBy="idcard", cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
} }

常见操作:

 @Test
public void save() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("YL");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();//事务开始 User user = new User("ylll");
user.setIdcard(new IDCard("123456789012345678")); em.persist(user); em.getTransaction().commit();
em.close();
factory.close();
}