logo

How to read data from BLOB using JPA (Hibernate)

How to read data from BLOB or CLOB using JPA (Hibernate) with annotation @Lob and @Basic. Presented on web application which loads images from MySQL database using Servlets.

In database you can have binary and character large objects (BLOB, CLOB). For example BLOBs can be used to store images or Microsoft documents (Word, Excel) and CLOBs can be used to store XML files. Both are mapped in your entity using @Lob annotation. Binary large object is mapped to an array of bytes, character large object is mapped to an array of chars or a String.


Usually you don't want to always retrieve these large objects from database. For this you can annotate them with @Basic annotation: @Basic(fetch=FetchType.LAZY).

 

Now I will show you typical usage of BLOB. I added to a CUSTOMERS table column ICON which is a BLOB and inside I put JPEG images of customers. Now in my web application I want to retrieve these data and show name and these images. To do so I created a class CustomerService where are two methods: list(), which loads all customers and loadImage() to retrieve an image of a selected customer.


Next I created two servlets. I could do this using Spring Web MVC, but for people that don't know Spring, I used servlets. CustomerServlet retrieves a list of customers and forwards to JSP file to display their information. CustomerImageServlet loads an image and sends it to client in binary form. Finally JSP file iterates all customers from CustomerServlet and uses img tag to load and show image of each customer.


comments powered by Disqus

rss

Free online Java web application examples

Want to develop whole web applications which use database, security and more? See my github account, where are lot's of example projects:
github

Search