1.背景介绍:对于每个人和身份证号的关系就是一对一
2.persistence.xml和前面完全一样
3.实体bean
IdCard.java
package com.sinoi.bean;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.OneToOne;//被维护端@Entitypublic class IdCard { @Id @GeneratedValue private Integer id; @Column(length=18, nullable=false) private String cardNo; @OneToOne(mappedBy="idCard", cascade={CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST}, optional=false) private Person person; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCardNo() { return cardNo; } public void setCardNo(String cardNo) { this.cardNo = cardNo; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } }
Person.java
package com.sinoi.bean;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;//维护端@Entitypublic class Person { @Id @GeneratedValue private Integer id; @Column(length=10, nullable=false) private String name; @OneToOne(cascade={CascadeType.ALL}, optional=false) @JoinColumn(name="per_id_for") private IdCard idCard; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public IdCard getIdCard() { return idCard; } public void setIdCard(IdCard idCard) { this.idCard = idCard; } }
4.测试
package junit.test;import javax.persistence.EntityManager;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;import org.junit.Test;import com.sinoi.bean.IdCard;import com.sinoi.bean.Person;public class UnitTest { @Test public void save() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("unitname"); EntityManager manager = factory.createEntityManager(); manager.getTransaction().begin(); IdCard idCard = new IdCard(); idCard.setCardNo("3408281990qqqqwwww"); Person person = new Person(); person.setName("bean"); idCard.setPerson(person); person.setIdCard(idCard); manager.persist(person);//为什么manager.persiste(idCard)会出现错误 manager.getTransaction().commit(); manager.close(); factory.close(); }}