Simple Hands on Hibernate

Hi,

In the below post will try to explain how to create simple Hibernate Project from crash.

Below is the scenario:
I have an EVENT table and want to insert one simple row in that table.
Here is the table script:



CREATE TABLE EVENT_DETAILS 
(
NAME VARCHAR2(20), 
LOCATION VARCHAR2(20), 
ID VARCHAR2(20) NOT NULL, 
CONSTRAINT EVENT_DETAILS_PK PRIMARY KEY (ID)
)


First, you need to download the Hibernate Distribution Bundle, you can get it here:

Extract the Zip file and use Hibernate.jar.
Here I downloaded "hibernate-distribution-3.6.8.Final" but we will be traditional mapping files in this example.

Now, create a new Java Project in eclipse. Say, "SampleBankPartyApp".
Create a folder structure under your project: "config/orm/hibernate/cfg" and "config/orm/hibernate/hbm"

Next, we need to create Hibernate Configuration file. Here I am using Oracle 11g database. You can change the confi file as per your requirement.

Below is my Hibernate configuration file: 
"hibernate.cfg.xml"

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@IP:PORT:SerivceName</property>
<property name="connection.username">xxxxx</property>
<property name="connection.password">xxxxx</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="../hbm/events.hbm.xml" />
</session-factory>
</hibernate-configuration>


Next, create an  Event DTO: "org.bank.domain.Event"
package org.bank.domain;

public class Event {
private String Name;
private String Place;
private String Event_ID;
public String getEvent_ID() {
return Event_ID;
}
public void setEvent_ID(String eventID) {
Event_ID = eventID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPlace() {
return Place;
}
public void setPlace(String place) {
Place = place;
}
}


Now, we have Event DTO and Event_Details Table. We need to map the attribute from DTO to column in Database. For that we need to create a mapping file. 
So create a mapping file at "config/orm/hibernate/hbm" and name it "events.hbm.xml".
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.bank.domain.Event" table="EVENT_DETAILS">
<id name="Event_ID" type="string">
<column name="ID" />
</id>
<property name="Name" column="NAME" />
<property name="Place" column="LOCATION" />
</class>
</hibernate-mapping>


Here you will observe that I have n't specified any type in property. This is because I have String in my class and Varchar2 in my Database. Hibernate try to find the best type for the above mapping. 
Note: The type mention in the mapping file are Hibernate types, not any java or database types.
As I have ID as primary key, I mentioned it in <ID> tag.

Now you have all stuff at place, you need a class to use this hibernate configuration and connect to database.
Lets create one:
Create a below class. org.bank.util.HibernateUtil 
package org.bank.util;

import java.net.URL;

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
//URL url = Thread.currentThread().getContextClassLoader()
// .getResource("config/orm/hibernate/cfg/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;
}
}


The above class contain a factory method that creates the instance of the SessionFactory at load time and its getSessionFactory() will return you the same instance every time. 

So now you have created Repository class, now create EventManager.java Class that will store the Java Object in  EventDetails Table.


package org.bank.app;



import org.bank.domain.Event;
import org.bank.util.HibernateUtil;
import org.hibernate.Session;


public class EventManager {


public static void main(String[] args) {
EventManager mgr = new EventManager();
Event SampleEvent = new Event();
SampleEvent.setName("NewYearParty");
SampleEvent.setPlace("JW");
SampleEvent.setEvent_ID("2");
mgr.createAndStoreEvent(SampleEvent);
HibernateUtil.getSessionFactory().close();
}


private void createAndStoreEvent(Event event_id) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
//Save the Object to Database
session.save(event_id);

session.getTransaction().commit();
}
}

/**
Now we have all the classes and configuration file ready, lets configure our Java project to make it run
**/

1. First, we need to add hibernate.cfg.xml to class path in order to make it visible for our program.
Goto-> Run Configuration->classpath->advance->add external folder (Select the folder that contain config file. Refer below screenshot:















If you don't want to add the config file to class path, you can pass the location URL while creating SessionFactory.

//URL url = Thread.currentThread().getContextClassLoader()
// .getResource("config/orm/hibernate/cfg/hibernate.cfg.xml");

2. You need to add below jar's in order to make it Run.










Now, Run EventManager.java you will get the below output on console and Record will be added to you table.
Output:

log4j:WARN No appenders could be found for logger (org.hibernate.type.BasicTypeRegistry).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Hibernate: insert into EVENT_DETAILS (NAME, LOCATION, ID) values (?, ?, ?)


Here in this post I tried to explain, how to setup a simple Hibernate program to a Newbie. Do comment if you get any issues.



You now need to configure a logging system. Hibernate uses commons logging and provides two
choices: Log4j and JDK 1.4 logging. Most developers prefer Log4j: copy log4j.properties from
the Hibernate distribution in the etc/ directory to your src directory, next to hibernate.cfg.xml.
If you prefer to have more verbose output than that provided in the example configuration, you
can change the settings. By default, only the Hibernate startup message is shown on stdout.



Now will read a method to read the stored data.


Add below read method to your EventManager.java file

private List listEvents() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List result = session.createQuery("from Event").list();
session.getTransaction().commit();
return result;
}



private void readData(){
List eventsList=listEvents();

for (int i = 0; i < eventsList.size(); i++)
{
Event theEvent = (Event) eventsList.get(i);
System.out.println("Event Place:"+theEvent.getPlace()+" Name: "+theEvent.getName());
}
}



Call readData() from EventManager.java
Here we have used simple HQL query.
Note: for running this application you need to add antlr-2.7.6.jar in your class path, you can find this in hibernate distribution folder.

Thanks. 

Popular posts from this blog

JAVA embedding in Oracle SOA 12c

Passing/Receiving HTTP header in SOA BPEL

Integrating Weblogic with IBM MQ over JMS