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();
}
Recommended Articles
Exposing an Enterprise Java Bean as a Singleton: A Simple Approach
Learn how to use the @Singleton annotation to expose an Enterprise Java Bean as a single instance, ensuring thread-safe and efficient management of your application's resources.
Create Type Safe Instances Using EJB QL in Enterprise Java
Learn how to use EJB QL for type-safe object creation and property selection in Enterprise Java. #EnterpriseJava #EJBQL #TypeSafety
Configure Clustered Timer EJB 3 Services on WildFly with Database Storage
Learn how to configure clustered Timer EJB 3 services using a PostgreSQL database in WildFly. #WildFly #JavaEE #ClusteredEJB
Retrieve Transaction ID in Enterprise Java with WildFly and EJB CMT - A Step-by-Step Guide
Learn how to retrieve transaction IDs in Enterprise Java using WildFly and EJB CMT. Includes CLI commands for JBoss.