How to map a BLOB field with JPA?

@javax.persistence.Lob can be used to specify that the annotated field should be represented as BLOB (binary data) in the DataBase.

A Lob may be either a binary or character type.

Common use of @Lob is to annotate a HashMap field inside your Entity to store some of the object properties which are not mapped into DB columns. That way all the unmapped values can be stored in the DB in one column in their binary representation.

Example:

@Entity
public class Customer {
  @Id
  @GeneratedValue
  private long id;

  @Lob
  @Column(name = "DATA")
  private String data;

  @Lob
  @Column(name = "PHOTO")
  private byte[] photo;
  
}

The Lob annotation may be used in conjunction with the @ElementCollection, if annotated on the collection of basic type:

 @Lob
 @ElementCollection
 @CollectionTable(name = "items", joinColumns = @JoinColumn(name = "items_FK"))
 @Column(name = "ITEMS")
 private List<String> items;

With that in place, you can persist your Entity with the @Lob fields as follows:

 private static void persistEntity(EntityManagerFactory emf) throws Exception {
       
      Customer c = new Customer();
      report.setData("lots of data....");
      //some dummy image
      report.setPhoto(new byte[]{1, 2, 3, 2, 1, 3, 3, 1, 5, 6});
      report.setItems(Arrays.asList("item 1....", "item 2...."));

      System.out.println("-- Persisting entity --");
      System.out.println(report);

      em.getTransaction().begin();
      em.persist(c);
      em.getTransaction().commit();
      em.close();
  }
Found the article helpful? if so please follow us on Socials