Hibernate saveorUpdate method problem
- by umesh awasthi
Hi all,
i am trying to work on with Hibernate (Database side for first time) and some how struck in choosing best possible way to use saveOrUpdate or Save.Update
i have a destination POJO class and its other attributes which needs to be updated along with the Destination entity.
i am getting an XML file to be imported and i am using the following code to update/save the destination entity along with its attribute classes.
try{
getSessionFactory().getCurrentSession().beginTransaction();
getSessionFactory().getCurrentSession().saveOrUpdate(entity);
getSessionFactory().getCurrentSession().getTransaction().commit();
}
catch(Exception e){
getSessionFactory().getCurrentSession().getTransaction().rollback();
}
finally{
getSessionFactory().close();
}
everything is working fine untill i am using the same session instance.but later on when i am using the same XML file to update the destination PO for certain attributes it giving me the following error.
SEVERE: Duplicate entry 'MNLI' for key 'DESTINATIONID'
9 Jan, 2011 4:58:11 PM org.hibernate.event.def.AbstractFlushingEventListener performExecutions
SEVERE: Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:114)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:109)
at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:244)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2242)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2678)
at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79)
i am using UUID as primary key for the Destination table and in destination table i have a destination id which is unique.but i can understand that in the secodn case hibernate is not able to find if there is already an entry for the same destination in the DB and trying to execute insert statement rather than update.
one possible solution is i can user destinationid to check if there is already a destination inplace with the given id and based on the results i can issue save or update command.
my question is can this be achieve by any other good way..?
Thanks in advance