How to Load or Save Image using Hibernate – MySQL
Join the DZone community and get the full member experience.
Join For FreeThis 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:
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.
Hibernate Config
This configuration file contains the required info used to connect to the database.
Hibernate Util
The HibernateUtil class helps in creating the SessionFactory from the Hibernate configuration file.
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.
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.
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/
Opinions expressed by DZone contributors are their own.
Comments