JPA实体属性one-to-one关系映射

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();
		
	}
}




你可能感兴趣的:(jpa)