SQL Zone is brought to you in partnership with:

Loiane Groner, Brazilian, works as a Java/ Sencha evangelist. She has 7+ years of experience in web development. She is the ESJUG (Espirito Santo Java Users Group) and CampinasJUG (Campinas Java Users Group) leader and coordinator. Loiane is passionate about technology and programming. Also author of ExtJS 4 First Look book. Loiane is a DZone MVB and is not an employee of DZone and has posted 42 posts at DZone. You can read more from them at their website. View Full User Profile

How to Load or Save Image using Hibernate – MySQL

10.23.2011
| 22570 views |
  • submit to reddit

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, 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:

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:

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

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

Happy Coding!

From http://loianegroner.com/2011/10/how-to-load-or-save-image-using-hibernate-mysql/

Published at DZone with permission of Loiane Groner, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Robert Craft replied on Thu, 2012/01/26 - 5:55am

Hi Loiane, I was looking for some thing like you have posted here. It is really helpful for me. You can saver almost 49.152 MB in a flied blog in mysql interesting in sql server has used 350mb in the version 2000 .

Spring Security

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.