开发者

Hibernate deletion issue

开发者 https://www.devze.com 2022-12-30 00:19 出处:网络
I\'m trying to write a Java app that imports a data file. The process is as follows Create Transaction

I'm trying to write a Java app that imports a data file. The process is as follows

  1. Create Transaction
  2. Delete all rows from datatable
  3. Load data file into datatable
  4. Commit OR Rollback if any errors were encountered.

The data loaded in step 3 is mostly the same as the data deleted in step3.

The de开发者_StackOverflow社区letion is performed using the following

DetachedCriteria criteria = DetachedCriteria.forClass(myObject.class);
List<myObject> myObjects = hibernateTemplate.findByCriteria(criteria);
hibernateTemplate.deleteAll(myObjects);

When I then load the datafile, i get the following exception

nested exception is org.hibernate.NonUniqueObjectException: 
a different object with the same identifier value was already associated with the session:

The whole process needs to take place in transaction. And I don't really want to have to compare the import file / data table and then perform an insert/update/delete to get them into sync.

Any help would be appreciated.


Shortest answer, use session.merge()

Short answer, use plain jdbc hibernate is the wrong tool for this job.

Longer answer, see what your database tools support in this regard.
A solution could be to:

  1. rename table old_table
  2. create an new empty table
  3. import the data into the new table
  4. drop old_table

Your entire table would be locked in your use case so this should not be a problem.


First idea: did you try to flush() the Session after step #2?

Second idea: use the StatelessSession interface. You may have to extend HibernateTemplate for that since SPR-6202 and SPR-2495 are unresolved.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号