DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • The Ultimate Guide on DB-Generated IDs in JPA Entities
  • Custom Model Context Protocol (MCP) for NL2SQL: A Rigorous Evaluation Framework on Oracle Database
  • Using Arrow Flight SQL to Improve Data Transfer Performance in Apache Doris
  • Automating a Web Form With Playwright MCP and MySQL MCP

Trending

  • What Nobody Tells You About Multimodal Data Pipelines for AI Training
  • You Are Using Claude Wrong (And So Is Everyone You Know)
  • How to Test a PATCH API Request With REST-Assured Java
  • Integrating AI-Driven Decision-Making in Agile Frameworks: A Deep Dive into Real-World Applications and Challenges
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to Load or Save Image using Hibernate – MySQL

How to Load or Save Image using Hibernate – MySQL

By 
Loiane Groner user avatar
Loiane Groner
·
Oct. 24, 11 · Interview
Likes (2)
Comment
Save
Tweet
Share
98.0K Views

Join the DZone community and get the full member experience.

Join For Free

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:

Github: https://github.com/loiane/hibernate-image-example

BitBucket: https://bitbucket.org/loiane/hibernate-image-example/downloads

Happy Coding!

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

Hibernate MySQL Database

Opinions expressed by DZone contributors are their own.

Related

  • The Ultimate Guide on DB-Generated IDs in JPA Entities
  • Custom Model Context Protocol (MCP) for NL2SQL: A Rigorous Evaluation Framework on Oracle Database
  • Using Arrow Flight SQL to Improve Data Transfer Performance in Apache Doris
  • Automating a Web Form With Playwright MCP and MySQL MCP

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook