Home » Java » Enterprise Java » Load or Save Image using Hibernate – MySQL

About Loiane Groner

Load or Save Image using Hibernate – MySQL

This tutorial will walk you throughout how to save and load an image from database (MySQL) using Hibernate.

Requirements

For this sampel project, we are going to use:

  • Eclipse IDE (you can use your favorite IDE);
  • MySQL(you can use any other database, make sure to change the column type if required);
  • Hibernate jars and dependencies (you can download the sample project with all required jars);
  • JUnit – for testing (jar also included in the sample project).

PrintScreen

When we finish implementing this sample projeto, it should look like this:

Database Model

Before we get started with the sample projet, we have to run this sql script into MySQL:

DROP SCHEMA IF EXISTS `blog` ;
CREATE SCHEMA IF NOT EXISTS `blog` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
USE `blog` ;

-- -----------------------------------------------------
-- Table `blog`.`BOOK`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `blog`.`BOOK` ;

CREATE  TABLE IF NOT EXISTS `blog`.`BOOK` (
  `BOOK_ID` INT NOT NULL AUTO_INCREMENT ,
  `BOOK_NAME` VARCHAR(45) NOT NULL ,
  `BOOK_IMAGE` MEDIUMBLOB NOT NULL ,
  PRIMARY KEY (`BOOK_ID`) )
ENGINE = InnoDB;

This script will create a table BOOK, which we are going to use in this tutorial.

Book POJO

We are going to use a simple POJO in this project. A Book has an ID, a name and an image, which is represented by an array of bytes.

As we are going to persist an image into the database, we have to use the BLOB type. MySQLhas some variations of BLOBs, you can check the difference between them here. In this example, we are going to use the Medium Blob, which can store L+ 3 bytes, whereL< 2^24.

Make sure you do not forget to add the column definition on the Column annotation.

package com.loiane.model;

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

@Entity
@Table(name="BOOK")
public class Book {

 @Id
 @GeneratedValue
 @Column(name="BOOK_ID")
 private long id;

 @Column(name="BOOK_NAME", nullable=false)
 private String name;

 @Lob
 @Column(name="BOOK_IMAGE", nullable=false, columnDefinition="mediumblob")
 private byte[] image;

 public long getId() {
  return id;
 }

 public void setId(long id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public byte[] getImage() {
  return image;
 }

 public void setImage(byte[] image) {
  this.image = image;
 }
}

Hibernate Config

This configuration file contains the required info used to connect to the database.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/blog</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
     <property name="connection.pool_size">1</property>
     <property name="show_sql">true</property>
    </session-factory>
</hibernate-configuration>

Hibernate Util

The HibernateUtil class helps in creating the SessionFactory from the Hibernate configuration file.

package com.loiane.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import com.loiane.model.Book;

public class HibernateUtil {

 private static final SessionFactory sessionFactory;

 static {
  try {
   sessionFactory = new AnnotationConfiguration()
        .configure()
        .addPackage("com.loiane.model") //the fully qualified package name
        .addAnnotatedClass(Book.class)
        .buildSessionFactory();

  } catch (Throwable ex) {
   System.err.println("Initial SessionFactory creation failed." + ex);
   throw new ExceptionInInitializerError(ex);
  }
 }

 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
}

DAO

In this class, we created two methods: one to save a Book instance into the database and another one to load a Book instance from the database.

package com.loiane.dao;

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

import com.loiane.hibernate.HibernateUtil;
import com.loiane.model.Book;

public class BookDAOImpl {

 /**
  * Inserts a row in the BOOK table.
  * Do not need to pass the id, it will be generated.
  * @param book
  * @return an instance of the object Book
  */
 public Book saveBook(Book book)
 {
  Session session = HibernateUtil.getSessionFactory().openSession();
  Transaction transaction = null;
  try {
   transaction = session.beginTransaction();
   session.save(book);
   transaction.commit();
  } catch (HibernateException e) {
   transaction.rollback();
   e.printStackTrace();
  } finally {
   session.close();
  }
  return book;
 }

 /**
  * Delete a book from database
  * @param bookId id of the book to be retrieved
  */
 public Book getBook(Long bookId)
 {
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   Book book = (Book) session.get(Book.class, bookId);
   return book;
  } catch (HibernateException e) {
   e.printStackTrace();
  } finally {
   session.close();
  }
  return null;
 }
}

Test

To test it, first we need to create a Book instance and set an image to the image attribute. To do so, we need to load an image from the hard drive, and we are going to use the one located in the images folder. Then we can call the DAO class and save into the database.

Then we can try to load the image. Just to make sure it is the same image we loaded, we are going to save it in the hard drive.

package com.loiane.test;

import static org.junit.Assert.assertNotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.loiane.dao.BookDAOImpl;
import com.loiane.model.Book;

public class TestBookDAO {

 private static BookDAOImpl bookDAO;

 @BeforeClass
 public static  void runBeforeClass() {
  bookDAO = new BookDAOImpl();
 }

 @AfterClass
 public static void runAfterClass() {
  bookDAO = null;
 }

 /**
  * Test method for {@link com.loiane.dao.BookDAOImpl#saveBook()}.
  */
 @Test
 public void testSaveBook() {

  //File file = new File("images\\extjsfirstlook.jpg"); //windows
  File file = new File("images/extjsfirstlook.jpg");
        byte[] bFile = new byte[(int) file.length()];

        try {
         FileInputStream fileInputStream = new FileInputStream(file);
         fileInputStream.read(bFile);
         fileInputStream.close();
        } catch (Exception e) {
         e.printStackTrace();
        }

        Book book = new Book();
        book.setName("Ext JS 4 First Look");
        book.setImage(bFile);

        bookDAO.saveBook(book);

        assertNotNull(book.getId());
 }

 /**
  * Test method for {@link com.loiane.dao.BookDAOImpl#getBook()}.
  */
 @Test
 public void testGetBook() {

  Book book = bookDAO.getBook((long) 1);

  assertNotNull(book);

  try{
         //FileOutputStream fos = new FileOutputStream("images\\output.jpg");  //windows
         FileOutputStream fos = new FileOutputStream("images/output.jpg");
            fos.write(book.getImage());
            fos.close();
        }catch(Exception e){
         e.printStackTrace();
        }
 }
}

To verify if it was really saved, let’s check the table Book:

and if we right click…

and choose to see the image we just saved, we will see it:

Source CodeDownload

You can download the complete source code (or fork/clone the project – git)from:

Githubhttps://github.com/loiane/hibernate-image-example

BitBuckethttps://bitbucket.org/loiane/hibernate-image-example/downloads

Happy Coding!

Reference: How to Load or Save Image using Hibernate – MySQL from our JCG partner Loiane Groner at the Loiane Groner’s blog blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

One comment

  1.  Nice! Very helpful, thank you very much.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


nine − 4 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.