Friday, November 12, 2010

How to start working with Hibernate

Introduction of Hibernate

Detailed introduction can be found in various good books and tutorials however I am just giving the basic idea about hibernate.

Hibernate is a solution for object relational mapping and a persistence management solution or persistent layer. In other words : Lets assume you have an application with some features containing some business logic and you need to save data in the database. All the business logic resides in Java code which works with Objects, where your database (mysql, postgresql etc...) are not all deal with objects. Hibernate provides a solution to map database tables to a class.


There are few steps to start working with hibernate

1) Basic setup for hibernate
2) Create Database / tables
3) Create POJO for tables
4) Mapping POJO with DB table
5) Hibernate configuration
6) Log4j configs
7) Run the example


Basic setup for Hibernate

a) Install jdk1.5.x/1.6.x, JAVA_HOME and PATH must be set correctly.
b) download and extract zip/tar file of Eclipse IDE (I used Galileo).
c) download the following jars* from http://hibernate.org
ant-1.6.2.jar
ant-antlr-1.6.2.jar
ant-junit-1.6.2.jar
ant-launcher-1.6.2.jar
antlr-2.7.4.jar
ant-swing-1.6.2.jar
asm-3.3.jar
c3p0-0.8.5.jar
cglib-2.2.jar
cleanimports.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
concurrent-1.3.2.jar
connector.jar
dom4j-1.5.2.jar
ehcache-1.1.jar
ejb3-persistence-3.3.2.Beta1.jar
hibernate-3.2.6.ga.jar
hibernate3.jar
hibernate-annotations-3.4.0.GA.jar
hibernate-commons-annotations-3.1.0.GA.jar
hibernate-core-3.3.0.SP1.jar
hibernate-entitymanager-3.4.0.GA.jar
hibernate-search-3.0.1.GA.jar
hibernate-validator-3.0.0.ga.jar
jaas.jar
jacc-1_0-fr.jar
jaxen-1.1-beta-4.jar
jboss-cache.jar
jboss-common.jar
jboss-jmx.jar
jboss-remoting.jar
jboss-system.jar
jdbc2_0-stdext.jar
jgroups-2.2.7.jar
jta.jar
junit-3.8.1.jar
log4j-1.2.9.jar
mysql-connector-java-3.0.16-ga-bin.jar
mysql-connector-java-3.1.6-bin.jar
oscache-2.1.jar
postgresql-8.2-504.jdbc3.jar
proxool-0.8.3.jar
swarmcache-1.0rc2.jar
versioncheck.jar
xerces-2.6.2.jar
xml-apis.jar

*some are not required e.g. if you are using mysql as your database then postgresql-8.2-504.jdbc3.jar is not required.

Create DB table (Postgres SQL) :

|--------------------------------------------------------------------|

CREATE TABLE "public"."emp" (
id SERIAL,
name text,
dob date
PRIMARY KEY(id)
);
|--------------------------------------------------------------------|

Create POJO Employee

package net.vs.example;

public class Employee {

private Integer id;

private String name;

private Date dob;

public Employee(){

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Date Dob() {

return dob;

}

public void Dob(Date dob) {

this.date = date;

}


Mapping POJO with DB table

You can use XML or annotations to define, how to map your class attributes to a database table.
Create the Employee.hbm.xml in the package net.vs.example and change it to the following

PostgreSQL Version:

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=net.vs.example.Employee table=emp>

<id name="id" column="id">

<generator class="sequence">

<param name="sequence"> emp_id_seq param>

generator>

id>

<property name="name" column = "name"/>

<property name="dob" column="dob" />

class>

hibernate-mapping>



Hibernate configuration

Create a file named “hibernate.cfg.xml” in your root directory
Insert the following in your hibernate file.


PostgreSQL Version:

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="connection.url">

jdbc:postgresql://localhost:5432/myDB

property>

<property name="connection.username"> myuser property>

<property name="connection.driver_class">org.postgresql.Driverproperty>

<property name="dialect">org.hibernate.dialect.PostgreSQLDialectproperty>

<property name="connection.password">mypwdproperty>


<property name="hibernate.show_sql">trueproperty>

<mapping resource="employee.hbm.xmll" />

session-factory>

hibernate-configuration>


Configuring Log4J

As you can see above we added the log4j library. This library does like a configuration file in thesource directory or it welcomes you with the following error.

log4j:WARN No appenders could be found for logger (TestClient).

log4j:WARN Please initialize the log4j system properly.


Create a file named log4j.properties in the root directory and insert the following:

### direct log messages to stdout ###

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.Target=System.out

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=debug, stdout

log4j.logger.org.hibernate=info

#log4j.logger.org.hibernate=debug

### log HQL query parser activity

#log4j.logger.org.hibernate.hql.ast.AST=debug

### log just the SQL

log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###

log4j.logger.org.hibernate.type=info

### log schema export/update ###

log4j.logger.org.hibernate.tool.hbm2ddl=info

### log HQL parse trees

#log4j.logger.org.hibernate.hql=debug

### log cache activity ###

log4j.logger.org.hibernate.cache=info

### log transaction activity

#log4j.logger.org.hibernate.transaction=debug

### log JDBC resource acquisition

#log4j.logger.org.hibernate.jdbc=debug

### enable the following line if you want to track down connection ###

### leakages when using DriverManagerConnectionProvider ###

#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace



Run the example


TestHibernate.java

public class TestHibernate{

public static void main(String agrs[]) {

Session session = null;
try {

SessionFactory factory = new Configuration().configure().buildSessionFactory();
session = factory.openSession();

Employee emp = new Employee();
emp.setName("John");
emp.setDob(new Date());

session.save(emp);

} catch(Exception be){
be.printStackTrace();
}
finally {
// Actual contact insertion will happen at this step
if (null!=session){
session.flush();
session.close();
}

}

}


Cheers !