Tuesday, August 10, 2010

Some Typical Hibernate Operations

First some concepts of Hibernate. Hibernate defines the following object states:
  • Transient - an object is transient if it is just created but has no primary key (identifier) and not associated with session.
  • Persistent - The object is in persistent state if session is open, and you just saved the instance in the database or retrieved the instance from the database.
  • Detached - a detached instance is an object that has been persistent, but its Session has been closed. A detached instance can be reattached to a new Session at a later point in time, making it persistent again. After detached state, object comes to persistent state if you call lock() or update() method.
In the following code, Spring is used. HibernateTemplate is a Spring class.

1. To Load and Update an Object from Database
HibernateTemplate hTemplate = getHibernateTemplate();
MyDto dto = (MyDto)hTemplate.load(MyDto.class, myObjectId);
dto.setUpdatedBy(user.getUsername());
dto.setUpdatedDt(new Date());
dto.setStatus(status);
hTemplate.flush();

2. To Update an Object Whose Hibernate State may be Transient or Detached
HibernateTemplate hTemplate = getHibernateTemplate();
// myDto is an input. It may be in transient or detached state
MyDto persistentDto = (MyDto) hTemplate.merge(myDto);
hTemplate.update(persistentDto);
Note: The merge method returns an object in the persistent state

3. To Load and Initialize an Object
MyDto dto = (MyDto) getHibernateTemplate().load(MyDto.class,myObjectId);
Hibernate.initialize(dto);
Or use the following that does not need initialization:
Mydto dto= (MyDto) getHibernateTemplate().get(MyDto.class, myObjectId);

References

  1. Hibernate Reference Documentation Version 3.2.2

No comments:

Post a Comment