I'm trying to write a Java app that imports a data file. The process is as follows
- Create Transaction
- Delete all rows from datatable
- Load data file into datatable
- 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:
- rename table old_table
- create an new empty table
- import the data into the new table
- 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.
精彩评论