Wednesday, January 20, 2010

An Example for "dirty checking" in Hibernate

As I have written about the features of hibernate in the previous post.One of them was dirty checking by hibernate.
Now what does dirty checking actually means?To see this practically lets look at the following class with name Computer.

public class Computer
{
private String name;
private Double prize;
public Computer()
{
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Double getPrize()
{
return prize;
}
public void setPrize(Double prize)
{
this.prize = prize;
}
}
Here I have prize and name as class attributes and I have setter and getter for them.Also I make the name attribute as the primary key in the .hbm.xml file.
Now lets have a class(say Manager) which deals with the retrieval of the row of table Computer,which looks as given bellow


public class Manager
{
public static void main(String[] args)
{
Configuration config = new Configuration();
config.configure();
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Computer c = (Computer)session.load(Computer.class, new String("Mac"));
System.out.println(c.getName());
System.out.println(c.getPrize());
c.setPrize(111111);=========>imp. step
session.getTransaction().commit();
session.flush();
session.close();
}
}
Now here when I make the prize of the computer as 111111 in the imp. step, and after the execution of Manager class gets over and I go to the DB and see that the value of the prize has been changed to 111111.
Now the point to be noted is that we changed prize to a new value and did not do a explicit save after changing the value(by calling session.save(c)),but still the changes are made.This auto-updating of DB with reference to the change in the object is called "dirty checking" in terms of Hibernate.

8 comments: