Hibernate 5 - Save and load image file example

Hibernate 5 - Save and load image file example

Technologies used:   JDK 1.8.0_121 | Hibernate 5.2.6.Final | Maven 3.3.9 | MySQL 5.7.12 | Eclipse Mars.2 (4.5.2)

In this post, we will learn how to save an image to and load an image from a database using the Hibernate ORM framework.

BLOB (Binary Large Object) data type is used to store images or binary files into a database.

The @Lob JPA annotation is used to map the java.sql.Blob or byte[] array to a BLOB column in a table.

Let’s write a sample hibernate program to store an image into a database.

 

Create an Entity class

First create an entity class Product to store image of a product.

Use @Lob annotation to map the java.sql.Blob type with BLOB column in a table.

Product.java

package com.boraji.tutorial.hibernate.entity;

import java.sql.Blob;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "PRODUCT")
public class Product {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name = "ID")
   private long id;

   @Column(name = "NAME")
   private String name;

   @Column(name = "IMAGE")
   private Blob image;

   //Getters and setters 
   //....
   //....
}

 

Create a Hibernate utility class

Create a helper class HibernateUtil to bootstrap hibernate.

Map the Product entity using the #MetadataSources.addAnnotatedClass() method.

HibernateUtil.java

package com.boraji.tutorial.hibernate;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import com.boraji.tutorial.hibernate.entity.Product;

/**
 * @author imssbora
 */
public class HibernateUtil {
  private static StandardServiceRegistry registry;
  private static SessionFactory sessionFactory;

  public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
      try {
        StandardServiceRegistryBuilder registryBuilder = 
            new StandardServiceRegistryBuilder();

        Map<String, String> settings = new HashMap<>();
        settings.put("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
        settings.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/BORAJI");
        settings.put("hibernate.connection.username", "root");
        settings.put("hibernate.connection.password", "admin");
        settings.put("hibernate.show_sql", "true");
        settings.put("hibernate.hbm2ddl.auto", "update");

        registryBuilder.applySettings(settings);

        registry = registryBuilder.build();

        MetadataSources sources = new MetadataSources(registry)
            .addAnnotatedClass(Product.class);

        Metadata metadata = sources.getMetadataBuilder().build();

        sessionFactory = metadata.getSessionFactoryBuilder().build();
      } catch (Exception e) {
        System.out.println("SessionFactory creation failed");
        if (registry != null) {
          StandardServiceRegistryBuilder.destroy(registry);
        }
      }
    }
    return sessionFactory;
  }

  public static void shutdown() {
    if (registry != null) {
      StandardServiceRegistryBuilder.destroy(registry);
    }
  }
}

 

Save an image into a database

Create a main class to save an image into a database as follows.

ImageSaveExample.java

package com.boraji.tutorial.hibernate;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.engine.jdbc.BlobProxy;

import com.boraji.tutorial.hibernate.entity.Product;

/**
 * @author imssbora
 */
public class ImageSaveExample {
   public static void main(String[] args) {
      Session session = null;
      Transaction transaction = null;
      try {
         session = HibernateUtil.getSessionFactory().openSession();
         transaction = session.getTransaction();
         transaction.begin();
         
         Product product=new Product();
         product.setName("Java - The Complete Reference");
         session.doWork(conn->{
            product.setImage(BlobProxy.generateProxy(getImage()));
         });
         session.save(product);
         transaction.commit();
         
         System.out.println("Product is saved successfully.");
         
      } catch (Exception e) {
         if (transaction != null) {
            System.out.println("Transaction is being rolled back.");
            transaction.rollback();
         }
         e.printStackTrace();
      } finally {
         if (session != null) {
            session.close();
         }
      }

      HibernateUtil.shutdown();
   }

   public static byte[] getImage() {
      File file =new File("Java.png");
      if(file.exists()){
         try {
            BufferedImage bufferedImage=ImageIO.read(file);
            ByteArrayOutputStream byteOutStream=new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", byteOutStream);
            return byteOutStream.toByteArray();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
      return null;
   }
}

Output

Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into PRODUCT (IMAGE, NAME, ID) values (?, ?, ?)
Product is saved successfully.

 

Load an image from a database

Create a main class to load an image from a database as follows.

ImageLoadExample.java

package com.boraji.tutorial.hibernate;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.boraji.tutorial.hibernate.entity.Product;

/**
 * @author imssbora
 */
public class ImageLoadExample {
   public static void main(String[] args) {
      Session session = null;
      Transaction transaction = null;
      try {
         session = HibernateUtil.getSessionFactory().openSession();
         transaction = session.getTransaction();
         transaction.begin();

         Product product = session.get(Product.class, 4L);
         System.out.println("Product Name: "+product.getName());
         
         InputStream imgStream = product.getImage().getBinaryStream();
         saveImage(imgStream);

         transaction.commit();
      } catch (Exception e) {
         if (transaction != null) {
            transaction.rollback();
         }
         e.printStackTrace();
      } finally {
         if (session != null) {
            session.close();
         }
      }

      HibernateUtil.shutdown();
   }

   public static void saveImage(InputStream stream) {
      File file = new File("output.png");
      try(FileOutputStream outputStream = new FileOutputStream(file)) {
         BufferedImage bufferedImage = ImageIO.read(stream);
         ImageIO.write(bufferedImage, "png", outputStream);
         System.out.println("Image file location: "+file.getCanonicalPath());
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

Hibernate: select product0_.ID as ID1_0_0_, product0_.IMAGE as IMAGE2_0_0_, product0_.NAME as NAME3_0_0_ from PRODUCT product0_ where product0_.ID=?
Product Name: Java - The Complete Reference
Image file location: D:\Work\Workspace BORAJI.COM\hibernate-save-image-example\output.png

You can download the complete example from the below download link.