JPA之OneToOne关系处理

在很早学习关系数据库的时候学过一对多,多对一,一对一,多对多的关系。之前已经介绍了1对多和多对一的关系。现在来看看1对1.

[color=red] 业务需求:一般情况下,一个人都只有一个身份证号码(特殊情况除外)。[/color]

下面给出人和身份证实体类

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 Person {
private Integer id;
private String name;
private IDCard idcard;

public Person(){}

public Person(String name){
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;
}
}



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 Person person;

public IDCard(){}

public IDCard(String cardno) {
this.cardno = cardno;
}
this.person = person;
}
@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;
}

@OneToOne(mappedBy="idcard",cascade={CascadeType.REFRESH,CascadeType.MERGE,CascadeType.REFRESH})
public Person getPerson() {
return person;
}
public void setPerson(Person person) {

}

测试类

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.junit.BeforeClass;
import org.junit.Test;

import cn.itcast.bean.IDCard;
import cn.itcast.bean.Person;

public class OneToOneTest {

@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test public void add(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin(); // start transaction
Person person = new Person("蒋笃淅");
person.setIdcard(new IDCard("88888888888"));
em.persist(person);
em.getTransaction().commit(); //commit transaction
em.close();
factory.close();
}
}

[b]总结:1对1其实可以参考[url=http://jiangduxi.iteye.com/blog/646693]1对多[/url]进行考虑,它的关系维护端由编写者自己去定义。
[/b]

你可能感兴趣的:(JPA,junit,Bean,Blog)