Hibernate Blob Data Type

In this tutorial I will show you how store and retrieve BLOB object using Hibernate Mapping file.

First create a new Java Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml


1. Sql Script

Use the following Sql Script for creating table.

create table User(
    User_ID int(10) primary key NOT NULL AUTO_INCREMENT,
    Name varchar(50),
    content longblob NOT NULL);

2. Pojo

Now create User class and write the following code.

package com.kruders.model.bean;

import java.sql.Blob;

public class User {
	private int userId;
    private String name;
    private Blob content;

	public int getUserId() {
		return userId;

	public void setUserId(int userId) {
		this.userId = userId;

	public String getName() {
		return name;

	public void setName(String name) {
		this.name = name;

	public Blob getContent() {
		return content;

	public void setContent(Blob content) {
		this.content = content;

3. Hibernate Mapping File

Now create HBM file PurchaseOrder.hbm.xml that maps classes to database tables.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	<class name="com.kruders.model.bean.User" table="USER">
		<meta attribute="class-description">This class contains user details.
		<id name="userId" type="int" column="USER_ID">
			<generator class="native" />
		<property name="name" type="string" length="50" column="NAME" />
		<property name="content" type="blob" column="content" />

4. Hibernate Configuration File

Now create the hibernate configuration file and add all the mapping files.

<?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:3306/test</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"></property>
    <property name="connection.pool_size">1</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
    <mapping resource="com/kruders/model/bean/User.hbm.xml"/>

5. Hibernate Utility Class

Now create HibernateUtil class. The HibernateUtil class helps in creating the SessionFactory from the Hibernate configuration file. A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances. A org.hibernate.Session represents a single-threaded unit of work. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once.

package com.kruders.util;

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;

6. Run Program

Create Main.java class that stores and retrieves BLOB object and run it as Java Application.

I have used byte array to store the data and then it is converted to BLOB.

package com.kruders.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Blob;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.kruders.model.bean.User;
import com.kruders.util.HibernateUtil;

public class Main {
   public static void main(String args[]) {
	    Session session = HibernateUtil.getSessionFactory().openSession();
	    Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            File resume = new File("D:\\Resume.doc");
            byte[] fileContent = new byte[(int) resume.length()];
            try {
       	     	FileInputStream fileInputStream = new FileInputStream(resume);
       	     	//convert file into array of bytes
            } catch (Exception e) {
            Blob blob = Hibernate.createBlob(fileContent);
            User user = new User();
        }catch (HibernateException e) {
        } finally {
    public static void readResume(Integer userId) {
    	Session session = HibernateUtil.getSessionFactory().openSession();
	    Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            List employees = session.createQuery("from User where userId ='" + userId + "'").list();
            for (Iterator iterator = employees.iterator(); iterator.hasNext();) {
                User user = (User) iterator.next();
                Blob blob = user.getContent();
                FileOutputStream fos = new FileOutputStream("D:\\Resume1.doc"); 
                fos.write(blob.getBytes(1, (int)blob.length()));
        } catch (HibernateException e) {
        } catch (Exception e) {
        } finally {

The folder structure of the example is shown below in Figure 20.1

Figure 20.1 Figure 20.1

You can download the source code of this example here.

One Response to Hibernate Blob Data Type