欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JPA OneToOne映射

程序员文章站 2022-04-21 10:13:29
...
package com.jvwl.model;

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;
/**
 * Person实体
 * @author Jerval
 *
 */
@Entity
public class Person {
	private Integer id;
	private String name;
	private IDCard idCard;

	public Person() {
	}

	public Person(String name) {
		super();
		this.name = name;
	}

	@Id
	@GeneratedValue
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Column(length = 10)
	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.jvwl.model;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
/**
 * 身体证实体
 * @author Jerval
 *
 */
@Entity
public class IDCard {

	private Integer id;
	private String cardNo;
	private Person person;

	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(nullable = false, length = 18)
	public String getCardNo() {
		return cardNo;
	}

	public void setCardNo(String cardNo) {
		this.cardNo = cardNo;
	}

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

	public void setPerson(Person person) {
		this.person = person;
	}
}

 

Test:

package junit.test;

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

import org.junit.Test;

import com.jvwl.model.IDCard;
import com.jvwl.model.Person;

public class JPATest {
@Test public void test(){
	EntityManagerFactory factory = Persistence.createEntityManagerFactory("jvwl");
	EntityManager em = factory.createEntityManager();
	em.getTransaction().begin();
	Person person = new Person("李菏");
	person.setIdCard(new IDCard("12212121"));
	em.persist(person);
	em.getTransaction().commit();
	em.close();
	factory.close();
}
}

 

 

相关标签: JPA junit