JPA教程 – JPA Lob延迟加载示例
我们可以通过仅提取频繁访问的数据来优化检索实体时的性能。如果需要,可以提取剩余的数据。
当使用@Lob注释将字节数组或字符数组字段映射到数据库时,我们可以设置是否对该字段执行延迟加载。
延迟加载使应用程序运行速度更快,因为JPA只在加载字节数组或字符数组时才使用它们。
基本映射的获取类型可以配置为通过在相应的@Basic注释中指定fetch元素来延迟或急切加载。
FetchType枚举类型定义此元素的值,可以是EAGER或LAZY。
@Basic(fetch=LAZY) @Lob @Column(name="PIC") private byte[] picture;
例子
下面的代码来自PersonDaoImpl.java。
package cn.w3cschool.common; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.springframework.transaction.annotation.Transactional; @Transactional public class PersonDaoImpl { public void test() { Professor emp = new Professor(); emp.setId(1); emp.setName("name"); emp.setSalary(12345); em.persist(emp); } @PersistenceContext private EntityManager em; }
以下代码来自Professor.java。
package cn.w3cschool.common; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; import static javax.persistence.FetchType.LAZY; @Entity public class Professor { @Id private int id; private String name; private long salary; @Basic(fetch=LAZY) @Lob @Column(name="PIC") private byte[] picture; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getSalary() { return salary; } public void setSalary(long salary) { this.salary = salary; } public byte[] getPicture() { return picture; } public void setPicture(byte[] picture) { this.picture = picture; } public String toString() { return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary() + " pic: " + new String(getPicture()); } }
下载 Lab_Lazy_Load.zip
以下是数据库转储。
Table Name: PROFESSOR Row: Column Name: ID, Column Type: INTEGER: Column Value: 1 Column Name: NAME, Column Type: VARCHAR: Column Value: name Column Name: PIC, Column Type: BLOB: Column Value: null Column Name: SALARY, Column Type: BIGINT: Column Value: 12345