JPAエンティティ属性one-to-one関係マッピング
2863 ワード
package com.lc.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;
import javax.persistence.Table;
@Entity
@Table(name="persons")
public class Person {
private Integer id;
private String name;
private IDCard idcard;
@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;
}
/*
*
*/
public Person() {
}
//
public Person(String name) {
super();
this.name = name;
}
}
package com.lc.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;
@Entity
public class IDCard {
private Integer id;
private String cardno;
private 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;
}
// mappedBy
@OneToOne(mappedBy = "idcard", cascade = { CascadeType.PERSIST,
CascadeType.MERGE, CascadeType.REFRESH }, optional = false)
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public IDCard(String cardno) {
this.cardno = cardno;
}
public IDCard() {
}
}
package com.lc.junitTest;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.Test;
import com.lc.bean.IDCard;
import com.lc.bean.Person;
public class OneToOneTest {
@Test
public void save() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpatest");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
//
Person person = new Person(" ");
IDCard idcard = new IDCard("1111122222");
idcard.setPerson(person);
person.setIdcard(idcard);
em.persist(person);
em.getTransaction().commit();
em.close();
factory.close();
}
}