Thursday, June 11, 2009

Hibernate Automatic Dirty Checking

Hibernate persistent objects are keep synchronize with database while the session is remain open. But the data will not commit to the database unless we call session.flush() or committing transaction.

Hibernate tracks all persistent objects and it call update statements only for updated objects. This process of monitoring persistence objects and updating only modified object is called automatic dirty checking.

This process is leads to improve performance of updating database.

Hibernate Persistence Lifecycle

Hibernate persistence lifecycle has 3 states.

1. Transient
2. Persistent
3. Detached

Transient State

When create object using new operator, it is immediately goes to transient state. In this state the object is not connected with database and it is in memory. In this state if object is dereference, then it is goes to detached mode and garbage collector will clean it. To move object to persistent state you have to save this. If you create object from persist data, then the object is not in Transient state and it is in persistent state since the object is connected with database.

Persistent State

When the object is referred to the valid database row, the object is in persistent state. When we call the delete() method, the data in database will remove and object will move to transient state.

Detached State

The persistent objects are holding data even after the transaction is completed. These objects will be detached from database when we close the session. You can detached object by calling evict() method.

Wednesday, June 10, 2009

Sample Hbm File

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>
<!--
This is a simplified version of the Event class used to
demonstrate proxies.
-->
<class name="Event" table="events">
<id name="id" column="uid" type="long" unsaved-value="null">
<generator class="assigned"/>
</id>
<property name="name" type="string" length="100"/>
<property name="startDate" column="start_date"
type="date"/>
<property name="duration" type="integer"/>
<many-to-one name="location" column="location_id"
class="Location"/>
</class>
</hibernate-mapping>

Sample Hibernate Config File

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//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/hibernatetutorial</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>

Sample HQL

HQL example:

Query query = session.createQuery("from Table as tbl where tbl.column = :myId");

query.setParameter("myId", myId);

List result = query.list();

JDBC Connection Sample

package mycom;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import com.mysql.jdbc.ResultSet;

public class testConnection {


public static void main(String[] args){

Connection conn = null;

try{

Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");

if(conn==null)
System.out.println("Connection is null");
else
System.out.println("Connection = "+conn.toString());


java.sql.ResultSet rs = null;
Statement stmt = conn.createStatement();

rs = stmt.executeQuery("select * from country order by 1");

while(rs.next()){
System.out.print(rs.getString(1)+" | ");
System.out.println(rs.getString(2));
System.out.println("-----------------------------------");
}

}catch(SQLException e){
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}finally{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}




}



}

Tuesday, June 9, 2009

What is Hibernate Session

Session is hibernate construct which is used to mediate connection with database.

At the time session is created, it is creating connection with database (Hibernate is use configurations given by configuration file to make the connection). Then session is holding connection until session ends. All objects loaded by Hibernate are associated with session. When session is ends Hibernate will automatically close the connection.

To use Hibernate persistence mechanism you have to initialize the Hibernate environment and then need to get session object from SessionFactory class. I'm showing below how to obtain session from SessionFactory .

// initializing Hibernate environment
Configuration cfg = new Configuration().configure();

// create session factory
SessionFactory factory = cfg.buildSessionFactory();

// getting the new session object
Session session = factory.openSession();

Monday, June 8, 2009

Why Hibernate

In this post I’ll discuss why Hibernate and what it gives.

It makes your development easy and more productive. As I discussed in my previous post, it maps your objects (POJO) with relational database. This automatic mapping of java object to database and vice versa is called Transparent Persistence. And this will reduce lot of coding from your program and also reduce the potential number of errors.

Hibernate lets you to change your database without doing any change to your program. For an example you can change your MySQL database to Oracle by just changing dialect of Hibernate configuration file to Oracle. So your application is database independent.

With Hibernate you don’t need to write messy SQl queries. Instead you can write object queries (HQL) and Hibernate will do rest for you.

Hibernate is provides you automatic versioning and time stamping. By using this, you can ensure that the changers done by one person to the database will not rollback by another user unintentionally. To enable this you need to define version type field in your application. Every time you modify particular record of database, Hibernate updates this version. Hibernate always check this version when you save data. So Hibernate is not allowing you to update particular record with older version of it.

Optimize performance. Hibernate is cache querying data in application workspace. So it improves the performance if application reads same data many times for same write.

What is Hibernate

Hibernate is an Object Relational Mapping solution and also supports to persistence management. If you are new to Object Oriented Programming and Hibernate, the above explanation will not give much sense to you. So let me explain it further.

Let’s say we have object called “Hotel” (Hotel.class) in our object oriented program and we need to persist (Save) it in the database where we have table called “Hotel”. In traditional way you need to read properties of object (Hotel) and create SQL statement and execute it to save in database.

But you don’t need to do this manual mapping when you use Hibernate. Hibernate is take care of this one to one mapping for you and persist it in database.

I’ll discuss this further in my later posts and feel free to enter any comments if you have on this post. So I can improve this for you.