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.

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


The following code is from

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;

public class PersonDaoImpl {
  public void test() {

    Professor emp = new Professor();


  private EntityManager em;

The following code is from

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;

public class Professor {
  private int id;
  private String name;
  private long salary;
  @Lob @Column(name="PIC")
  private byte[] picture;

  public int getId() {
      return id;
  public void setId(int id) { = id;
  public String getName() {
      return name;
  public void setName(String 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());


The following is the database dump.

    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