How to Load or Save Image using Hibernate – MySQL

October 18, 2011 | By | 9 Comments

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:

hibernate image loiane 01 How to Load or Save Image using Hibernate   MySQL

Database Model

hibernate image loiane 02 How to Load or Save Image using Hibernate   MySQL

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

DROP SCHEMA IF EXISTS <code>blog</code> ;
CREATE SCHEMA IF NOT EXISTS <code>blog</code> DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
USE <code>blog</code> ;

-- -----------------------------------------------------
-- Table <code>blog</code>.<code>BOOK</code>
-- -----------------------------------------------------
DROP TABLE IF EXISTS <code>blog</code>.<code>BOOK</code> ;

CREATE  TABLE IF NOT EXISTS <code>blog</code>.<code>BOOK</code> (
  <code>BOOK_ID</code> INT NOT NULL AUTO_INCREMENT ,
  <code>BOOK_NAME</code> VARCHAR(45) NOT NULL ,
  <code>BOOK_IMAGE</code> MEDIUMBLOB NOT NULL ,
  PRIMARY KEY (<code>BOOK_ID</code>) )
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, where L < 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:

hibernate image loiane 03 How to Load or Save Image using Hibernate   MySQL

and if we right click…

hibernate image loiane 04 How to Load or Save Image using Hibernate   MySQL

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

hibernate image loiane 05 How to Load or Save Image using Hibernate   MySQL

Source Code Download

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!

Filed in: Hibernate | Tags: , , , , , ,

Comments (9)

Links to this Post

  1. JavaPins | January 8, 2012
  1. jjzd2w

    You can saver almost 49.152 MB in a flied blog in mysql interesting in sql server has used 350mb in the version 2000 .

    nice article happy coding !!

  2. dsuzette

    Great article, thanks for such a complete example, I’m able to set up my project and run this in a snap!!!

  3. liliedryana

    really good explanation about the image. 
    Is it going to be the same for PDF or WORD or other text file?

  4. Greetings from Istanbul, this is a very simple and easily understandable tutorial. Thank you.

  5. Vikrant

    nice article….thanx alot for the same.

  6. Vikrant

    nice article…thanx alot for the same.

  7. dtelaroli

    Thanks Loiane.
    Simple and work fine.

Leave a Reply

Trackback URL | RSS Feed for This Entry