Hibernate – save image into database
To save an image into database, you need to define a table column as blob data type in MySQL, or equivalent binary type in others database. In Hibernate side, you can declare a byte array variable to store the image data.
Here’s an Maven project to use Hibernate to save an image into MySQL ‘avatar‘ table.
1. Table creation
An avatar table creation script in MySQL.
CREATE TABLE `mkyong`.`avatar` (
`AVATAR_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`IMAGE` blob NOT NULL,
PRIMARY KEY (`AVATAR_ID`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
2. Maven dependency
Add Hibernate and MySQL dependency.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.common</groupId>
<artifactId>HibernateExample</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>HibernateExample</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- MySQL database driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<!-- Hibernate framework -->
<dependency>
<groupId>hibernate</groupId>
<artifactId>hibernate3</artifactId>
<version>3.2.3.GA</version>
</dependency>
<!-- Hibernate library dependecy start -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
<!-- Hibernate library dependecy end -->
</dependencies>
</project>
3. Avatar Model
Create a model class to store the avatar data. The image data type is array of bytes.
Avatar.java
package com.mkyong.common;
public class Avatar implements java.io.Serializable {
private Integer avatarId;
private byte[] image;
public Avatar() {
}
public Avatar(byte[] image) {
this.image = image;
}
public Integer getAvatarId() {
return this.avatarId;
}
public void setAvatarId(Integer avatarId) {
this.avatarId = avatarId;
}
public byte[] getImage() {
return this.image;
}
public void setImage(byte[] image) {
this.image = image;
}
}
4. Mapping file
Create a Hibernate mapping file for avatar. The data type for image is binary.
Avatar.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.mkyong.common.Avatar" table="avatar" catalog="mkyong">
<id name="avatarId" type="java.lang.Integer">
<column name="AVATAR_ID" />
<generator class="identity" />
</id>
<property name="image" type="binary">
<column name="IMAGE" not-null="true" />
</property>
</class>
</hibernate-mapping>
5. Hibernate configuration file
Hibernate configuration file to define the database connection and Hibernate mapping file.
hibernate.cfg.xml
<?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.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyong</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/mkyong/common/Avatar.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
6. Hibernate utility
A Hibernate utility class to get the database connection.
HibernateUtil.java
package com.mkyong.persistence;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
7. Run it
Read a file “C:\\mavan-hibernate-image-mysql.gif” and save it into database, later get it from database and save it into another image file “C:\\test.gif“.
package com.mkyong.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.hibernate.Session;
import com.mkyong.persistence.HibernateUtil;
public class App
{
public static void main( String[] args )
{
System.out.println("Hibernate save image into database");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
//save image into database
File file = new File("C:\\mavan-hibernate-image-mysql.gif");
byte[] bFile = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
//convert file into array of bytes
fileInputStream.read(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Avatar avatar = new Avatar();
avatar.setImage(bFile);
session.save(avatar);
//Get image from database
Avatar avatar2 = (Avatar)session.get(Avatar.class, avatar.getAvatarId());
byte[] bAvatar = avatar2.getImage();
try{
FileOutputStream fos = new FileOutputStream("C:\\test.gif");
fos.write(bAvatar);
fos.close();
}catch(Exception e){
e.printStackTrace();
}
session.getTransaction().commit();
}
}
Done.
I am trying to store the data into mysql using hibernate but i am getting the following exception.
Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column ‘data’ at row 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2973)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1600)
at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1129)
at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:681)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1368)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1283)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1268)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
… 58 more
While Creating the table, define LONGBLOB for the image. It will fix this error.
Can anyone advise me whether the code downloaded from this website can be run in Android Studio?
I failed to run it. Is there a way to test the code? Please help. Thanks.
This code is running well and useful.
Image file should convert to byte first then save to database..
Thanks Mykong
Bad
Just save the image path in plain text (String). Your method will make your database server slower to retrieve data. Stop that shit!
how can we do it please let me know
This example is helpfull for me while im storing image into database statically.
But i have to upload image dynamically. Using servlet jsp . In hibernate.
Thanks
Thank you!
Hi mkyong,
Similarly I want to store my .zip file in mysql database using hibernate framework in java.I tried the same thing that using byte array, I stored my .zip file .Here I faced a problem that ,I got the database session and able to save my class unfortunately it stops at transaction&commit. can you please help me how to overcome this issue!
Thanks in advance!
Thanks, nice post
cant we implement this hibernate like in this url :
https://mkyong.com/spring/maven-spring-hibernate-mysql-example/
what is difference if i implement in the above urls way
thanks bro i did insert image by help of your code.
byte[] bAvatar = avatar2.getImage(); when I retrieve Byte array from Database and trying to create image again on secondary storage. Its not creating any image.
Hi MKYong,
Why after downloaded the example source code, I cannot load it inside Android Studio 1.2.2?
Please advise and help. Thanks.
hi, can somebody help me on how to save/ retrieve image using Java Servlets from MySQL DB in JSP / HTML5 as view
Is there any library or method to save only the reference to the file and keep the data in the fs? I mean, something that handle the directory creation, filenaming and so on.
Thanks
Configuration().configure().buildSessionFactory() is deprecated.
Configuration cfg = new Configuration().configure();
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties());
cfg.buildSessionFactory(ssrb.build());
how to save video instead of image…. I did the same but the type in database display tinyblob and because of less space i m not able to save video… POlease suggest
We can use Hibernate.createBlob(new FileInputStream(file2)) and Property mapping as in hbm.Xml file
Hello,I am using Oracle 10g and hibernate 4.2.1. I have written DAO as same as that of u but when i map image column as binary…Its gives me following error…”Caused by: java.sql.SQLException: ORA-01461: can bind a LONG value only for insert into a LONG column” I tried a lot but not getting the point though i know the meaning of error..bt where to change the code nt getting..
Thank you for this article.
Question:
What if I do not know the image extension when I get it from db? (should I store ext. to? how?)
Awesome example. Thanks a lot.
java.sql.SQLException: Data size bigger than max size for this type: 369881
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
at oracle.jdbc.ttc7.TTCItem.setArrayData(TTCItem.java:95)
at oracle.jdbc.dbaccess.DBDataSetImpl.setBytesBindItem(DBDataSetImpl.java:2414)
at oracle.jdbc.driver.OraclePreparedStatement.setItem(OraclePreparedStatement.java:1134)
at oracle.jdbc.driver.OraclePreparedStatement.setBytes(OraclePreparedStatement.java:2170)
at org.hibernate.type.AbstractBynaryType.set(AbstractBynaryType.java:43)
at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:83)
at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:60)
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:1932)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2178)
… 11 more
I am getting above error when i try to insert text file in the database,and i declared it as Blob datatype in oracle 11g,and i ma using hibernate to insert into database
Exception in thread “main” java.lang.NoClassDefFoundError: javax/transaction/Synchronization
at org.hibernate.impl.SessionImpl.(SessionImpl.java:213)
at org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:473)
at org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:497)
at org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:505)
at com.mkyong.common.App.main(App.java:15)
gives me this error when i try to run app.java
This is a nice tutorial indeed. Though it is a bad practice to keep images or all other files in database but still proves worthy for some small to midsize project when there is no file server available. Here is another short and simple tutorial we have in our website on BLOB and image handling – http://www.techcubetalk.com/2013/05/workshop-developing-mini-photo-gallery-application-using-struts2-hibernate-mysql-blob-part-1/
Thanks Myokong, your jpa/hibernate examples are great – you always show step by step instruction which is very useful. I am working on a hibernate project and your examples really help! Please keep posting more examples! By the way, would be great if you can also provide an example for working with Oracle XML column type (XMLType) using hibernate.
How i can retrive an image using hibernate and display that image on jsf2.0…
thank you for this nice tutorial !
but i see that the part //Get image from database, generate the images stored in DB on a disk directory ,which is redundant ,we have two images .
is there a better solution to open the image in a jsf page without creating the image on the disk.
Hello mkyong,
i want to save and get a pdf file in data base in stead of image .
what will be the changes to this tutorial !
thx for your help
Hi zakaria,Whether this will work for .zip file?
Thanks in advance
Byte array can support any file type. No change.
yes, there is no changes and the tuto works perfectly !
Mr.Mkyong ,you’re my hero this summer . i work in a project this with jsf-spring-hibernate ,and your tuto concerning these technologies helped me lot . god bless you !
in my project i’ve student with CV and Motivation letter that i should store in data base ,and consult it from a JSF ( when you consult a student informations ,you should have a link to the cv and LM that you click and it will be opened ).
i want to do this work using jsf-spring-hibernate . if you could help me ,i’ll be thankful !
thank you for everything .
i have uploaded image to data base and retrieved image from data base.
Suppose i retrieved object name Customer having following attributes id(long),name(String) , Image(byte array). I have set it in model attribute and got object in View but now how to display this Image in HTML.
Please help..
Hello mkyong,
I am getting this error for second part of code.
If u can please assist me,
“java.io.FileNotFoundException: C:\test.jpg (Access is denied)”
even if file is present or file is not present.
thanks in advance 🙂