Sunday, January 3, 2016

Hibernate - Difference between session.get() and session.load()

Ref:- http://www.mkyong.com/hibernate/different-between-session-get-and-session-load/

1. session.load()

  • It will always return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just look like a temporary fake object.
  • If no row found , it will throws an ObjectNotFoundException.

2. session.get()

  • It always hit the database and return the real object, an object that represent the database row, not proxy.
  • If no row found , it return null.

It’s about performance

Hibernate create anything for some reasons, when you do the association, it’s normal to obtain retrieve an object (persistent instance) from database and assign it as a reference to another object, just to maintain the relationship. Let’s go through some examples to understand in what situation you should use session.load().

1. session.get()

For example, in a Stock application , Stock and StockTransactions should have a “one-to-many” relationship, when you want to save a stock transaction, it’s common to declared something like below
           
        Stock stock = (Stock)session.get(Stock.class, new Integer(2));
           StockTransaction stockTransactions = new StockTransaction();
           //set stockTransactions detail
           stockTransactions.setStock(stock);        
           session.save(stockTransactions);

Output

Hibernate: 
    select ... from mkyong.stock stock0_ 
    where stock0_.STOCK_ID=?
Hibernate: 
    insert into mkyong.stock_transaction (...) 
    values (?, ?, ?, ?, ?, ?)
In session.get(), Hibernate will hit the database to retrieve the Stock object and put it as a reference to StockTransaction. However, this save process is extremely high demand, there may be thousand or million transactions per hour, do you think is this necessary to hit the database to retrieve the Stock object everything save a stock transaction record? After all you just need the Stock’s Id as a reference to StockTransaction.

2. session.load()

In above scenario, session.load() will be your good solution, let’s see the example,
           
        Stock stock = (Stock)session.load(Stock.class, new Integer(2));
           StockTransaction stockTransactions = new StockTransaction();
           //set stockTransactions detail
           stockTransactions.setStock(stock);        
           session.save(stockTransactions);

Output

Hibernate: 
    insert into mkyong.stock_transaction (...) 
    values (?, ?, ?, ?, ?, ?)
In session.load(), Hibernate will not hit the database (no select statement in output) to retrieve the Stock object, it will return a Stock proxy object – a fake object with given identify value. In this scenario, a proxy object is enough for to save a stock transaction record.

Exception

In exception case, see the examples

session.load()

Stock stock = (Stock)session.load(Stock.class, new Integer(100)); //proxy

 //initialize proxy, no row for id 100, throw ObjectNotFoundException
System.out.println(stock.getStockCode());
It will always return a proxy object with the given identity value, even the identity value is not exists in database. However, when you try to initialize a proxy by retrieve it’s properties from database, it will hit the database with select statement. If no row is found, a ObjectNotFoundException will throw.
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: 
[com.mkyong.common.Stock#100]

session.get()

//return null if not found
Stock stock = (Stock)session.get(Stock.class, new Integer(100)); 
System.out.println(stock.getStockCode()); //java.lang.NullPointerException
It will always return null , if the identity value is not found in database.

Conclusion

There are no always correct solution, you have to understand the differential in between, and decide which method is best fix in your application

Hibernate - Transient, Persistent and Detached Objects in Hibernate

Ref:- http://www.dineshonjava.com/p/transient-persistent-and-detached.html#.VnIeEfkrLIU


1. Transient State:
    A New instance of  a persistent class which is not associated with a Session, has no representation in the database and no identifier value is considered transient by Hibernate:
  1. UserDetail user = new UserDetail();  
  2. user.setUserName("Dinesh Rajput");  
  3. // user is in a transient state  
2. Persistent State:
    A persistent instance has a representation in the database , an identifier value and is associated with a Session. You can make a transient instance persistent by associating it with a Session:
  1. Long id = (Long) session.save(user);  
  2. // user is now in a persistent state  
3. Detached State:
    Now, if we close the Hibernate Session, the persistent instance will become a detached instance: it isn't attached to aSession anymore (but can still be modified and reattached to a new Session later though).
  1. session.close();  
  2. //user in detached state  
Difference between Transient and Detached States:
Transient objects do not have association with the databases and session objects. They are simple objects and not persisted to the database. Once the last reference is lost, that means the object itself is lost. And of course , garbage collected. The commits and rollbacks will have no effects on these objects. They can become into persistent objects through the save method calls of Session object.

The detached object have corresponding entries in the database. These are persistent and not connected to the Session object. These objects have the synchronized data with the database when the session was closed. Since then, the change may be done in the database which makes this object stale. The detached object can be reattached after certain time to another object in order to become persistent again.

Lets see in the following example to save or update the user data...
  1. package com.sdnext.hibernate.tutorial;  
  2.   
  3. import org.hibernate.Session;  
  4. import org.hibernate.SessionFactory;  
  5. import org.hibernate.cfg.AnnotationConfiguration;  
  6.   
  7. import com.sdnext.hibernate.tutorial.dto.UserDetails;  
  8.   
  9. public class HibernateTestDemo {  
  10.  /** 
  11.   * @param args 
  12.   */  
  13.  public static void main(String[] args)   
  14.  {  
  15.   UserDetails userDetails = new UserDetails();  
  16.                 userDetails.setUserName("Dinesh Rajput");  
  17.                 userDetails.setAddress("Noida City");  
  18.   //Here 'userDetails' is TRANSIENT object  
  19.     
  20.                 SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();  
  21.   Session session = sessionFactory.openSession();  
  22.   session.beginTransaction();  
  23.     
  24.    session.save(userDetails);  
  25.   //Here 'userDetails' is PERSISTENT object  
  26.    userDetails.setUserName("User Updated after session close");  
  27.   
  28.                 session.getTransaction().commit();  
  29.   session.close();  
  30.   //Here 'userDetails' is DETACHED object  
  31.  }  
  32. }  


Hibernate - State Changes of Object in Hibernate

Ref:- http://www.dineshonjava.com/p/understanding-state-changes-of-object.html#.VnIfgPkrLIU

  1. Transient State 
  2. Persistent State
  3. Detached State
Now you will learn how to flow of object in these states and how to manage by the hibernate.Look in the following figures-

1. When Creating a new Entity Object 

Here we see when create an object it is in transient state in this state hibernate does not ask for save this object means that in this state hibernate's session does not associate with that object in this state.
Once we calling session's save method now object move to the persistent state i.e. hibernate's session associated with that object in this state if any change made in the object hibernate ask to the database and made change in the database also.
After done our required events when we calling session's close method then object moves in the  detached  state.

2. When Reading an Entity Object
 


Here we see that we are not getting new object from new operator, we get the object from session's get method. Here we pass a primary key in the get method and getting a persistent object.

3. When Delete an Entity Object


Here after getting persistent object from session of hibernate. When we are calling the delete method of the session object moves from persistent state to the transient state. If we calling the close method of the session then that object moves to the detached state. If once object move to the transient state it never become a persistent object.

Now we look the states diagram of the entity object in the following.

 When object in the session area then it is in Persistent State.
 When object before the session area then it is in Transient State. 
 When object after the session area then it is in Detached State.

Detached to Persistent State:
 
Lets see in the following example how to an object moves from detached state to the persistent state again.
HibernateTestDemo.java
  1. package com.sdnext.hibernate.tutorial;  
  2.   
  3. import org.hibernate.Session;  
  4. import org.hibernate.SessionFactory;  
  5. import org.hibernate.cfg.AnnotationConfiguration;  
  6.   
  7. import com.sdnext.hibernate.tutorial.dto.UserDetails;  
  8.   
  9. public class HibernateTestDemo {  
  10.   
  11.  /** 
  12.   * @param args 
  13.   */  
  14.  public static void main(String[] args)   
  15.  {  
  16.   UserDetails userDetails = new UserDetails();  
  17.   //Here 'userDetails' is in TRANSIENT state  
  18.     
  19.   SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();  
  20.   Session session = sessionFactory.openSession();  
  21.   session.beginTransaction();  
  22.     
  23.   userDetails = (UserDetails) session.get(UserDetails.class, 1);  
  24.   //Here 'userDetails' is in PERSISTENT state  
  25.     
  26.   session.save(userDetails);  
  27.   session.getTransaction().commit();  
  28.   session.close();  
  29.     
  30.   session = sessionFactory.openSession();  
  31.   session.beginTransaction();  
  32.     
  33.   userDetails.setUserName("User Updated after session close");  
  34.   //Here 'userDetails' is in DETACHED state  
  35.     
  36.   session.update(userDetails);  
  37.   //Here 'userDetails' is again in PERSISTENT state  
  38.   session.getTransaction().commit();  
  39.   session.close();  
  40.  }  
  41. }  


Output:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select userdetail0_.USER_ID as USER1_0_0_, userdetail0_.ADDRESS as ADDRESS0_0_, userdetail0_.USER_NAME as USER3_0_0_ from User_Details userdetail0_ where userdetail0_.USER_ID=?
Hibernate: select userdetail_.USER_ID, userdetail_.ADDRESS as ADDRESS0_, userdetail_.USER_NAME as USER3_0_ from User_Details userdetail_ where userdetail_.USER_ID=?
Hibernate: update User_Details set ADDRESS=?, USER_NAME=? where USER_ID=?