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();
}
}
推荐阅读
-
PHP数据对象映射模式实例分析
-
Mybaits 源码解析 (八)----- 全网最详细,没有之一:结果集 ResultSet 自动映射成实体类对象(上篇)
-
JPA中实现双向多对多的关联关系(附代码下载)
-
持久层框架JPA与Mybatis该如何选型
-
c# 通过内存映射实现文件共享内存的示例代码
-
ps中渐变映射调整图层如何定义及其各项参数的使用技巧
-
由于扩展配置问题而无法提供您请求的页面。如果该页面是脚本,请添加处理程序。如果应下载文件,请添加 MIME 映射。
-
CDR曲线映射插件使用方法介绍
-
Spring-Data-JPA整合MySQL和配置的方法
-
Spring Data JPA例子代码[基于Spring Boot、Mysql]