saveOrUpdate Method in Hibernate
There is some bit of confusion with hibernate users as to what exactly saveorUpdate method does . saveOrUpdate is general purpose method that either saves a transient instance by generating a new identifier or updates/reattaches the detached instances associated with its current identifier.
I have seen people using saveOrUpdate() instead of an update. Hibernate doc clearly says that update() or saveOrUpdate() is to be used in the following scenario:
- the application loads an object in the first session
- the object is passed up to the UI tier
- some modifications are made to the object
- the object is passed back down to the business logic tier
- the application persists these modifications by calling
update()in a second session
saveOrUpdate() does the following:
- if the object is already persistent in this session, do nothing
- if another object associated with the session has the same identifier, throw an exception
- if the object has no identifier property,
save()it - if the object’s identifier has the value assigned to a newly instantiated object,
save()it - if the object is versioned by a
<version>or<timestamp>, and the version property value is the same value assigned to a newly instantiated object,save()it - otherwise
update()the object


pls I encounter this problem
-I have been able to save into the database using StoreDAO as the DAO class,but while trying to retrieve the values i get this error ..
Exception >>>>> [Ljava.lang.Object; cannot be cast to com.Hibernate.Test.StoreDAO
the code fragement is below:
List listVal = listEvents(sessionFactory.getCurrentSession());
System.out.println(“Size >>>>>>>>>>>>> ” + listVal.size());
for (int i = 0; i < listVal.size(); i++)
{
StoreDAO store = (StoreDAO)listVal.get(i);
System.out.println("City: " + store.getCity() + " State: " + store.getState());
}
the listevents () method :
private static List listEvents(Session sess)
{
sess.beginTransaction();
List result = sess.createSQLQuery("select * from HibernateStore").list();
sess.beginTransaction().commit();
return result;
}
why can't i cast the list object returned to the StoreDAO object?
@Ayojava, You can retrieve Entities using HQL like ‘Select storeDAO from StoreDAO storeDAO’ , where StoreDAO is the class name of the Entity.(class which you use to map to HibernateStore table). With Above HQL query you can retrieve values from HibernateStore table by
List listVal = listEvents(sessionFactory.getCurrentSession());
System.out.println(”Size >>>>>>>>>>>>> ” + listVal.size());
for (int i = 0; i < listVal.size(); i++)
{
StoreDAO store = (StoreDAO)listVal.get(i);
System.out.println("City: " + store.getCity() + " State: " + store.getState());
}
Hope this helps