HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Hibernate / Hibernate example of insert/select blob from database

Hibernate example of insert/select blob from database

In previous hibernate tutorials, we have learned about first level cache, second level cache and some various mapping examples etc. This is complete list of hibernate related tutorials. In this post, I am giving an example of inserting BLOB data into database using hibernate and getting this data from database, using hibernate entities.

In short, inserting and fetching BLOB data such as images requires two steps: define database column type as “BLOB” and have a field in entity of type “byte array”.

Lets take an example, in which, I am inserting “test.png” image from windows C drive to database (MySQL). Then I will read the image data again from database and store it to different location.

Hibernate entity

Please note, I have declared the data field as byte[].

@Entity
@Table(name = "TBL_IMAGES")
public class ImageWrapper implements Serializable {
	
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "ID", unique = true, nullable = false)
	private Integer id;
	
	@Column(name = "IMAGE_NAME", unique = false, nullable = false, length = 100)
	private String imageName;
	
	@Column(name = "DATA", unique = false, nullable = false, length = 100000)
	private byte[] data;
	
	//Getters and Setters
}

Inserting blob data into database

Let’s look at the code:

	Session session = HibernateUtil.getSessionFactory().openSession();
	session.beginTransaction();
		
	File file = new File("C:\test.png");
	byte[] imageData = new byte[(int) file.length()];

	try {
		FileInputStream fileInputStream = new FileInputStream(file);
		fileInputStream.read(imageData);
		fileInputStream.close();
	} catch (Exception e) {
		e.printStackTrace();
	}

	ImageWrapper image = new ImageWrapper();
	image.setImageName("test.jpeg");
	image.setData(imageData);

	session.save(image);	//Save the data
	
	session.getTransaction().commit();
	HibernateUtil.shutdown();

After executing above code, you can verify that a table into database is created if it’s not already there. And one BLOB column is created to hold the image data.

Hibernate blob example
Hibernate blob example

Reading the blob data from database

This is simple, and in fact you do not need to do anything extra. Above entity definition will work fine.

	Session session = HibernateUtil.getSessionFactory().openSession();
	session.beginTransaction();
	
	ImageWrapper imgNew = (ImageWrapper)session.get(ImageWrapper.class, 1);
	byte[] bAvatar = imgNew.getData();

	try{
		FileOutputStream fos = new FileOutputStream("C:\temp\test.png"); 
		fos.write(bAvatar);
		fos.close();
	}catch(Exception e){
		e.printStackTrace();
	}

	session.getTransaction().commit();
	HibernateUtil.shutdown();

Hibernate configuration

For reference, This is the configuration I am using for this example:

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.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
		<property name="hibernate.hbm2ddl.auto">create</property>
        <mapping class="hibernate.test.dto.ImageWrapper"></mapping>
    </session-factory>
</hibernate-configuration>

Also below is the code for HibernateUtil.java

HibernateUtil.java

public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();
	 
    @SuppressWarnings("deprecation")
	private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure(new File
            		("D:\Latest Setup\eclipse_juno_workspace\hibernate-test-project\hibernate.cgf.xml"))
            		.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() {
    	getSessionFactory().close();
    }
}

If still feeling trouble, download the sourcecode attached.

Sourcecode Download

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Ganesh

    September 16, 2016

    Hi,

    I want to read blob data from mysql and want to show in jsp file using hibernate.

    Can you help to do the same.

    Regards,
    Ganesh Pawar

    • Ganesh

      September 16, 2016

      image saved in blob data format.

  2. akhila

    May 29, 2014

    how to configure the hibernate.cfg.xml in sessionfactory. i am placed inside the src.
    it shows an error message

    ailed.org.hibernate.HibernateException: Could not parse configuration: /hibernate.cfg.xml
    Exception in thread “main” java.lang.ExceptionInInitializerError
    at com.sree.tribro.HibernateUtil.buildSessionFactory(HibernateUtil.java:25)
    at com.sree.tribro.HibernateUtil.(HibernateUtil.java:11)
    at com.sree.tribro.TestHibernate.main(TestHibernate.java:12)
    Caused by: org.hibernate.HibernateException: Could not parse configuration: /hibernate.cfg.xml
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2163)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:2075)
    at com.sree.tribro.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
    … 2 more
    Caused by: org.dom4j.DocumentException: Error on line 2 of document : The processing instruction target matching “[xX][mM][lL]” is not allowed. Nested exception: The processing instruction target matching “[xX][mM][lL]” is not allowed.
    at org.dom4j.io.SAXReader.read(SAXReader.java:482)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2155)
    …

    • Lokesh Gupta

      May 29, 2014

      Your file is in right place. It’s just not parseable. Open the file in Internet Explorer and edit it until it is loaded properly.

  3. akhila

    May 29, 2014

    Hai sir,
    How to upload .doc/.txt files using hibernate.I need urgent .
    plz help me.

  4. akhila

    May 29, 2014

    After running this code,I got a nullpointer Exception.please help me sir.

    • Lokesh Gupta

      May 29, 2014

      Give me the stacktrace

      • akhila

        May 29, 2014

        sir, already i was given but it shows a error message

        java.io.FileNotFoundException: C:ody.jpg (The filename, directory name, or volume label syntax is incorrect)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.(Unknown Source)
        at com.sree.tribro.TestHibernate.main(TestHibernate.java:19)
        Hibernate:
        select
        hibernate_sequence.nextval
        from
        dual
        Hibernate:
        select
        imagewrapp0_.id as id1_0_0_,
        imagewrapp0_.DATA as DATA2_0_0_,
        imagewrapp0_.IMAGE_NAME as IMAGE_NA3_0_0_
        from
        TBL_IMAGES imagewrapp0_
        where
        imagewrapp0_.id=?
        Exception in thread “main” java.lang.NullPointerException
        at com.sree.tribro.TestHibernate.main(TestHibernate.java:33)

        • Lokesh Gupta

          May 29, 2014

          It’s java.io.FileNotFoundException. File you are trying to insert is not found. Make sure path is correct. In path, do not use “”(backslash).. rather use “/” forward slash.

  5. Valerio

    February 14, 2014

    for PDF instead?? what can i use instead of ImageWrapper?

    • Lokesh Gupta

      February 14, 2014

      Rename the class ImageWrapper to PDFWrapper. Nothing special.

  6. Nicolas

    November 18, 2013

    What if..
    The file is bigger than the max Memory
    I mean, -Xmx512m and my file is 2Gig?

    • Lokesh Gupta

      November 18, 2013

      BLOB fields should be used for storing small files e.g. resumes (not necessarily). Storing 2 GB data in one row is not a good idea to me. Use file system instead and store file name and path in database.
      Even after this somebody needs to store 2 GB in database, then file must be spilted into multiple parts and store into multiple rows. On retrieval retrieve them all, and join them back.

Comments are closed on this article!

Search Tutorials

Hibernate Tutorial

  • Hibernate – Introduction
  • Hibernate – Hello World
  • Hibernate – Get/Fetch
  • Hibernate – Persist
  • Hibernate – Merge & Refresh
  • Hibernate – Get Entity Reference
  • Hibernate – BLOB
  • Hibernate – Save Update
  • Hibernate – Persistence LifeCycle
  • Hibernate – SessionFactory
  • Hibernate – Entities Equality
  • Hibernate – Cascade Types
  • Hibernate – Lazy Loading
  • Hibernate – Criteria Queries
  • Hibernate – HQL
  • Hibernate – Named Query
  • Hibernate – Mappings
  • Hibernate – First Level Cache
  • Hibernate – Second Level Cache
  • Hibernate – EhCache Configuration
  • Hibernate – OSCache Configuration
  • Hibernate – C3P0 Connection Pool
  • Hibernate – In memory Database
  • Hibernate – Bean Validation
  • Hibernate – Validator CDI
  • UnexpectedTypeException

Hibernate Annotations

  • Hibernate – JPA 2 Annotations
  • Annotations Vs Mappings
  • Hibernate – @Immutable
  • Hibernate – @NaturalId
  • Hibernate – @OneToMany
  • Hibernate – @ManyToMany
  • Hibernate – @OneToOne

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces