Hi All;
I have an application which truncates a table using the following sudo code
Code:
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session s = sessionFactory.openSession();
s.createQuery("delete from MyTable").exectueUpdate();
s.close();
The program then calls a webservice and reads in new data and attempts to store the new data back into the empty table. The code is similar to this :
Code:
public void repopulateTable( List<EntityObjects>eList){
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
int i = 0;
for( EntityObjects data : eList ){
s.save( data );
if( ( i % 20 ) == 0 ){
s.flush();
s.clear();
}
}
tx.commit();
s.close();
}
The program works fine the first time it is executed but if it is executed a second time Hibernate throws a Duplicate data exception. If instead of a save() I call saveOrUpdate() the code again executes fine the first time but the second time I get a StaleStateException. The sql that is being executed by Hibernate when it fails is an update to the table. It seems that Hibernate's context is not keeping track of the fact that the table data has been deleted and still thinks data exists in the table. When it accesses the table to perform the update it realizes the table is empty and throws the StaleStateException. When Hibernate attemps to save data to the empty table it references some mapped reference to the old data that it had previously saved but which is now deleted resulting in the Duplicate data exception. How do I resolve this seemingly "Catch 22" situation?
I should mention that we are using Hibernate 4.3.1.