Hibernate Persistance Example

Tuesday, July 14, 2009

I had seen many new deveopers looking for Hibernate Insertion example. So I decided to write a small Standalone example.

Below are the required jars to run this example which are easily availabel

asm.jar

cglib-2.1.jar

commons-collections

commons-logging

dom4j-1.4.jar

ehcache-1.1.jar

hibernate3.jar

jta.jar

log4j.jar

ojdbc14.jar

You can get all these jars in downloadable file which is located below.

I have developed this application using Eclipse IDE.




The following java class contains getSession(), closeSession() Methods.
HibernateUtil.java


package com.raj.test;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
* Configures and provides com.cgs.examz.bl.bo.access to Hibernate sessions,
* tied to the current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateUtil {

/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal threadLocal = new ThreadLocal();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;

private HibernateUtil() {
}

/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the SessionFactory if needed.
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();

if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}

/**
* Rebuild hibernate session factory
*/
public static void rebuildSessionFactory() {
try {

configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {

e.printStackTrace();
}
}

/**
* Close the single hibernate session instance.
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);

if (session != null) {
session.close();
}
}

/**
* return session factory
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}

/**
* return session factory
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateUtil.configFile = configFile;
sessionFactory = null;
}

/**
* return hibernate configuration
*/
public static Configuration getConfiguration() {
return configuration;
}
}


We have to write pojo class for contact table properties.
Contact.java


package com.raj.test;

public class Contact {
private String firstName;
private String lastName;
private String email;
private long id;

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}
}


After writing a pojo class we have to write one hibernate mapping file related to pojo.
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.raj.test.Contact" table="HIBERNATE_EXAMPLE">
<id name="id" type="long" column="ID">
<generator class="assigned"></generator>
</id>
<property name="firstName" type="string">
<column name="FIRSTNAME" />
</property>
<property name="lastName" type="string">
<column name="LASTNAME" />
</property>

<property name="email" type="string">
<column name="EMAIL" />
</property>
</class>
</hibernate-mapping>


In this hibernate config file we have to mention information related to connection.


at hostname we have to give database server host name and at sid we have to give corresponding id(or)name.
In this we have to map the hbm files



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">
oracle.jdbc.driver.OracleDriver
</property>
<property name="hibernate.connection.url">
jdbc:oracle:thin:@hostname:1521:sid
</property>
<property name="hibernate.connection.username">admin</property>
<property name="hibernate.connection.password">admin</property>
<property name="hibernate.dialect">
org.hibernate.dialect.OracleDialect
</property>
<property name="hibernate.connection.autocommit">true</property>
<property name="current_session_context_class">thread</property>
<property name="show_sql">true</property>


<mapping resource="com/raj/test/Contact.hbm.xml" />
</session-factory>
</hibernate-configuration>



FirstExample.java


package com.raj.test;

import org.hibernate.Session;

/**
* @author Nagaraju V
* Hibernate example to inset data into Contact table
*/
public class FirstExample {
public static void main(String[] args) {

System.out.println("In Main--->");
Session session = HibernateUtil.getSession();
Contact contact = new Contact();
contact.setId(3);
contact.setFirstName("Naga");
contact.setLastName("vee");
contact.setEmail("raj_veer@gmail.com");
session.save(contact);
session.beginTransaction().commit();

System.out.println("Record Inserted Sucessfully");
session.close();
}
}

We have to create table in database. The following table will shows database script.

hiberstand.sql


CREATE TABLE "HIBERNATE_EXAMPLE"
( "ID" NUMBER(30,0),
"FIRSTNAME" VARCHAR2(60 BYTE),
"LASTNAME" VARCHAR2(60 BYTE),
"EMAIL" VARCHAR2(60 BYTE)
)


Enjoy with this example (Persisting data into database)


Image Hosted by ImageShack.us

Image Hosted by ImageShack.us

0 comments: