JPA 一对一延迟加载示例

JPA教程 – JPA一对一延迟加载示例

以下代码显示如何使用延迟加载设置执行一对一映射。

  @OneToOne(fetch=LAZY)
  private Department department;

例子

下面的代码来自Person.java。

package cn.w3cschool.common;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import static javax.persistence.FetchType.LAZY;
@Entity
public class Person {
  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private long id;

  private String name;
  @OneToOne(fetch=LAZY)
  private Department department;

  public Person() {}

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

  public Department getDepartment() {
    return department;
  }

  public void setDepartment(Department department) {
    this.department = department;
  }

  public Long getId() {
    return id;
  }
  public void setId(Long id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }

  @Override
  public String toString() {
    return "Person [id=" + id + ", name=" + name + "]";
  }

}

下面的代码来自Department.java。

package cn.w3cschool.common;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Department {
  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private long id;

  private String name;

  public long getId() {
    return id;
  }

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

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

下面的代码来自PersonDaoImpl.java。

package cn.w3cschool.common;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

@Transactional
public class PersonDaoImpl {
  public void test(){
    Person p1 = new Person("Tom");

    p1.setName("Tom");

    Department d = new Department();
    d.setName("Design");
    p1.setDepartment(d);

    em.persist(p1);
    em.persist(d);
  }
  @PersistenceContext
  private EntityManager em;
}

下载 OneToOne_Lazy_Load.zip

以下是数据库转储。

Table Name: DEPARTMENT
 Row:
    Column Name: ID,
    Column Type: BIGINT:
    Column Value: 1

    Column Name: NAME,
    Column Type: VARCHAR:
    Column Value: Design

Table Name: PERSON
 Row:
    Column Name: ID,
    Column Type: BIGINT:
    Column Value: 1

    Column Name: NAME,
    Column Type: VARCHAR:
    Column Value: Tom

    Column Name: DEPARTMENT_ID,
    Column Type: BIGINT:
    Column Value: 1
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《JPA 一对一延迟加载示例》
文章链接:https://zhuji.vsping.com/293484.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。