JPA Lob延遲加載示例

2018-02-23 15:21 更新

JPA教程 - JPA Lob延遲加載示例


我們可以通過(guò)僅提取頻繁訪問(wèn)的數(shù)據(jù)來(lái)優(yōu)化檢索實(shí)體時(shí)的性能。如果需要,可以提取剩余的數(shù)據(jù)。

當(dāng)使用@Lob注釋將字節(jié)數(shù)組或字符數(shù)組字段映射到數(shù)據(jù)庫(kù)時(shí),我們可以設(shè)置是否對(duì)該字段執(zhí)行延遲加載。

延遲加載使應(yīng)用程序運(yùn)行速度更快,因?yàn)镴PA只在加載字節(jié)數(shù)組或字符數(shù)組時(shí)才使用它們。

基本映射的獲取類型可以配置為通過(guò)在相應(yīng)的@Basic注釋中指定fetch元素來(lái)延遲或急切加載。

FetchType枚舉類型定義此元素的值,可以是EAGER或LAZY。

  @Basic(fetch=LAZY)
  @Lob @Column(name="PIC")
  private byte[] picture;

例子

下面的代碼來(lái)自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;
}

以下代碼來(lái)自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

以下是數(shù)據(jù)庫(kù)轉(zhuǎn)儲(chǔ)。

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


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)