How to 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.


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).


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 <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_NAME</code> VARCHAR(45) NOT NULL ,
  PRIMARY KEY (<code>BOOK_ID</code>) )

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


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;

public class Book {

	private long id;
	@Column(name="BOOK_NAME", nullable=false)
	private String name;
	@Column(name="BOOK_IMAGE", nullable=false, columnDefinition="mediumblob")
	private byte[] image;
	public long getId() {
		return id;
	public void setId(long id) { = id;
	public String getName() {
		return name;
	public void setName(String 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"
        <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>

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()
								.addPackage("com.loiane.model") //the fully qualified package name
		} catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);

	public static SessionFactory getSessionFactory() {
		return sessionFactory;


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();;
		} catch (HibernateException e) {
		} finally {
		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) {
		} finally {
		return null;


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 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;

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

	public static void runAfterClass() {
		bookDAO = null;

	 * Test method for {@link com.loiane.dao.BookDAOImpl#saveBook()}.
	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);;
        } catch (Exception e) {
        Book book = new Book();
        book.setName("Ext JS 4 First Look");

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

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


        	//FileOutputStream fos = new FileOutputStream("images\\output.jpg");  //windows
        	FileOutputStream fos = new FileOutputStream("images/output.jpg"); 
        }catch(Exception e){

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 Code Download

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



Happy Coding!

9 thoughts on “How to Load or Save Image using Hibernate – MySQL

  1. 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. Great article, thanks for such a complete example, I’m able to set up my project and run this in a snap!!!

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

  4. Pingback: JavaPins

Comments are closed.