Recent Posts

Tuesday, 24 May 2016

Hibernate Session Methods


load() vs get()  
     Hibernate Session provides two method to access object e.g. session.get() and session.load(). Both looked quite similar to each other but there are many differences between load and get method which can affect performance of our application.

load()
1. Throws "org.hibernate.0bjectNotFoundException" if object is not found in cache as well as on database. As we can see the ObjectNotFoundException hierarchy, we can say this is un-checked exception. So we no need to write try-catch block to handle this exception.

2. It is lazy loading, means when we call session.load(Class, identifier) method it will not return entity object, it will return proxy object. When we try to access the non-identifier properties from the proxy object, at that time it will hit the database and load the entity object.

3. As Session.load() return proxy instance, so it is not fully available in any future detached state.

4. Use this method if it is sure that the objects exist.

5. It is just like EntityManager.getReference0 method of JPA.

get()
1. It will return 'null' value, if object is not found on cache as well as on database.

2. It is early loading, Means when we call session.load(Class, identifier) method it will hit the database immediately and load entity object and return entity object.

3. As Session.get() returns a fully initialized instance, so it is fully available in any future detached state.

4. Use this method if it is not sure that the objects exist.

5. It is just like EntityManager.find() method of JPA
Note:
1. If working with detached objects is not needed, load() or getReference() can be used to have better performance.

2. Session.load() or EntityManager.getReference() should be used if a fully initialized instance is not needed, which saves a database roundtrip if nothing other than creation of an association is done, with the proxied instance in managed state.

3. load() method exists prior to get() method which is added on user request.
When to use Session get() and load() in Hibernate
     If object present we have to implement some logic, if not we need to implement some other logic.
get(): if the object is not there, it returns null. Then we can implement above requirement as follows
if(object == null){
//some code
} else {
//some other logic
}

load(): if the object is not there it throws an exception. So we can't implement this requirement using load(). For the above requirement we go for get() method.

When update() method has to call ?
Transient state?
     Transient state means the object is not associated with session and not presented in database. When there is no record in the database, no question of updating the record: So when the object is in transient state we can't call update() method

Persistent state?
     Persistence state means the object is associated with session as well as presented in the database. If the object is in the persistent state then the object is said to be synchronized with database. 50 whatever modifications done to the object, those changes will be updated in the database and vice versa. So we no need to call update() method when object is in persistent state.

Detached state?
     Detached state means the object is not associated with session but presented In the database In this state if we want to do any modifications to the object we should call update() method. Because in this state the object is not synchronized with database.

public void saveOrUpdate(0biect object) throws HibernateException
     If the record is not there in the database it will try to insert the record. If the record is there in the database it will try to ,update the record.

public Connection close0 throws HibernateException
     Once the transaction is completed we need to close the session. When we close the session all the associated objects with the session will be de-associated from session and associated JDBC connection also closed. It is not strictly necessary to close the session but you must at least disconnect() it.
public void clear()
     This method is used to de-associate all the objects from session.
Application code
Session session = SessionUtil.getSession();
session.getTransaction().begin();
Account accountl = (Account)session.get(Account.class,1001);
Account account2 = (Account)session.get(Account.class,1002);
// Now accountl and account2 objects are in persistent state.
accountl.setName("Ashok Kumar");
account2.setName("Vinod Kumar");
session.clear();
// Now account1 and account2 objects are in detached state.
session.getTransaction().conimit();
* In the above example, when we call session.clear() method, accountl and account2 objects will be de-associated from the session object. i.e. account1 and account2 objects are moved from persistent state to detached state.

* Now accountl and account2 are in non-transactional state. So even we are committing the transaction the modified values of account1 and account2 are not updated in the database.
public void evict(Obiect object) throws HibernateException
     This method is used de-associates the specified object from session.
Application code
Session session = SessionUtil.getSession();
session.getTransaction().begin();
Account account1 = (Account)session.get(Account.class,1001);
Account account2 = (Account)session.get(Account.class,1002);
// Now accountl and account2 objects are in persistent state.
accountl.setName("New Ashok");
account2.setName("Vinod Kumar");
session.evict(account1);
// Now accountl in detached state and account2 in persistent state.
session.getTransaction().commit();
* evict() is used to de-associate specified object from the session object.

* In the above example when we call session.evict(account1) accountl object will be de-associated from session ,

* After calling transaction.commit(), only account2 object will be updated. Because it is in persistent state.
public boolean contains(Object object)
     It is used to check whether the object is associated with session or not.
Application code
Session session = SessionUtil.getSession();
Account account = (Account)session.get(Account.class,1001);
System.out.println("After Calling get() method");
if(session.contains(account)){
System.out.println("Account Is associated with session");
} else{
System.out.println("account is not associated with session");
}
session.clear();
System.out.println("After calling clear() method");
if(session.contains(account)){
System.out.println("account Is associated with session");
} else{
System.out.println("account is not associated with session");
}
public boolean isConnected()
     To check weather there is a connection is associated with the session or not.
Application Code
Session session = SessionUtil.getSession();
if(session.isConnected()){
System.out.println("connected");
}else{
System.out.println("not connected");
}
session.close();
if(session.isConnected()){
System.out.println("connected");
}else{
System.out.println("not connected");
}
public void flush() throws HibernateException
     This method is used to synchronize session data with database
Application Code
Session session = SessionUtil.getSession();
session.getTransaction().begin();
Account account = (Account)session.get(Account.class,1001);
account.setName("Ashok");
account.setBalance(9500);
session.flush();
System.out.println("Breank.. Point and observe the console..");
session.getTransaction().commit();
* In the above example when we call session.flush(), Hibernate checks or compares account object data and , corresponding record database. If it finds difference, it will execute update query to update object data into the database record.

* When transaction.commit() is called it will also check object data and corresponding record data. If it finds different it will update object data into database.

* So after transaction.commit(), we should not call sessioll.flush() because when we call transaction.cornrnit() session is in sync with database

Next Tutorial   Hibernate Batch Processing

Previous Tutorial  Persistent Object Life Cycle

No comments:

Post a Comment