JPA Tutorial - JPA Lob Lazy Load Example








We can optimize the performance when retrieving the entity by fetching only the data frequently accessed. The remainder of the data can be fetched if it is required.

When mapping byte array or char array field to database with @Lob annotation we can set if we would like to do the lazy loading for that field.

The lazy loading makes the application run faster since JPA only load the byte array or char array when we are about to use them.

The fetch type of a basic mapping can be configured to be lazily or eagerly loaded by specifying the fetch element in the corresponding @Basic annotation.

FetchType enumerated type defines the values for this element, which can be either EAGER or LAZY.

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




Example

The following code is from PersonDaoImpl.java.

package com.java2s.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;
}

The following code is from Professor.java.

package com.java2s.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());
  }
}


Download Lab_Lazy_Load.zip

The following is the database dump.

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