Monday, August 29, 2011

Hibernate - Store and Retrieve Data along with BLOB as XML

Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database.

Here, i have demostrated basic example to store data along with blob into Database and retrieve from Database.File logic is used to display Blob Data only. While writing your own Logic, you should avoid it.

Before Using this tutorial, You need know how hibernate Configuration "hibernate.cfg.xml" should look like. Read related blog post - Hibernate config file

Contact.java - Pojo file containing getter and setter methods.

package com.core;

import java.io.Serializable;
import java.sql.Blob;

/**
 * @author Anuj Patel
 * Java Core POJO class to map to database Contact Table
 */
public class Contact implements Serializable{
    private String firstName;
    private String lastName;
    private String email;
    private int id;  
    private Blob contactData;
  
    public Blob getContactData() {
        return contactData;
    }
    public void setContactData(Blob contactData) {
        this.contactData = contactData;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }    public void setLastName(String lastName) {
        this.lastName = lastName;
    }    public String getEmail() {
        return email;
    }    public void setEmail(String email) {
        this.email = email;
    }  
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
}


Hibernate Mapping XML : Actually mapping from Column to Table Column happening here
Contact.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.core.Contact" table="TBContact">
  <id name="id" type="int" column="id" >
  <generator class="assigned"/>
  </id>

<property name="firstName">
  <column name="firstName" />
  </property>
  <property name="lastName">
  <column name="lastName"/>
  </property>
  <property name="email">
  <column name="email"/>
  </property>
 
  <property name="contactData" type="java.sql.Blob">
  <column name="ObjXML" />
  </property>
  </class>
  </hibernate-mapping>


HibernateUtil.java - contains logic to initialized session factory
package com.configuration.hibernate;

import java.net.URL;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
 * @author Anuj J Patel
 */
public class HibernateUtil {
   private static final SessionFactory sessionFactory = buildSessionFactory();
     
    public static SessionFactory getSessionfactory() {
        return sessionFactory;
   }

    private static SessionFactory buildSessionFactory(){
        try{
            return new Configuration().configure().buildSessionFactory();   
        }
        catch(Throwable ex){
            System.err.println("initial sessionFactory creation failed"+ex);
            throw new ExceptionInInitializerError(ex);
        }       
   }
   
    public static void shutDown(){
        getSessionfactory().close();
    }
}

Java Program to Store Data into Database using Hibernate :
package com.Test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import com.configuration.hibernate.HibernateUtil;
import com.core.Contact;
import java.sql.Blob;
import java.sql.SQLException;

import com.thoughtworks.xstream.XStream;
/**
 * @author Anuj Patel
 */
public class AddDataIntoDB {

    private static XStream xstream = new XStream();
    private static Session session = null;

    public static void main(String[] args) throws SQLException, IOException {
        // TODO Auto-generated method stub

        boolean flag = false;
        try {
            session = new HibernateUtil().getSessionfactory().openSession();
            session.beginTransaction();

            xstream.alias("Contact", Contact.class);
           
              Contact contact = new Contact(); contact.setId(1);
              contact.setFirstName("Anuj"); contact.setLastName("patel");
              contact.setEmail("anuj@gmail.com");
             
              String contactXML = xstream.toXML(contact);
              File inf = new File("contactXMLFile.xml");
              FileWriter fw = new FileWriter(inf);
              BufferedWriter out = new BufferedWriter(fw);
              out.write(contactXML);
              out.close();
              fw.close();
             
              InputStream is = new FileInputStream(inf);
              Blob contactData = (Blob) Hibernate.createBlob(is);
              contact.setContactData(contactData);             
             
              session.save(contact);
              System.out.println("Writing to DB - Done!!");
             
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        } finally {
            // actually insertion happens at this place
            if (flag) {
                session.flush();
                session.close();
            }
        }
    }   
}

Java Program to retrieve Data from Database using Hibernate :
package com.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.hibernate.Query;
import org.hibernate.Session;
import com.configuration.hibernate.HibernateUtil;
import com.core.Contact;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
/**
 * @author Anuj Patel
 */
public class readfromDB {

    private static final String SELECT_STATEMENT = "from Contact where id = :ID";
    private static Session session = null;

    public static void main(String[] args) throws SQLException, IOException {
   
        boolean flag = false;
        try {
            session = new HibernateUtil().getSessionfactory().openSession();
            session.beginTransaction();

            Query query = session.createQuery(SELECT_STATEMENT);
            query.setParameter("ID",'1');
            List lst = query.list();
            Iterator it = lst.iterator();
            while(it.hasNext()){
                Contact contact = (Contact) it.next();
                System.out.println(contact.getId());
                System.out.println(contact.getFirstName() + " " + contact.getLastName());
                System.out.println(contact.getEmail());
       
                Blob blob = contact.getContactData();
                try {
                    int bufferlen = (int) blob.length();
                    byte[] buffer = new byte[bufferlen];
                   
                    File outf = new File("contactXMLFileRes.xml");
                    FileOutputStream fos = new FileOutputStream(outf);
                    InputStream ins = blob.getBinaryStream();
                    while (ins.read(buffer) &gt; 0) {
                        fos.write(buffer);
                      }
                    fos.close();   
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }               
            }
           
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        } finally {           
            if (flag) {
                session.flush();
                session.close();
            }
        }
    }   
}

No comments:

Post a Comment