Reputation: 1271
I have a requirement where I am updating rows according to uuid's where one uuid may be associated to more than one rows.
Here's the scenario: 4a90558c-4a5b-4af7-8c68-60ff81f74ef3 is my uuid and it exists in 8 columns in my DB.
and my java code is as follows:
try{
session = sessionFactory.getCurrentSession();
tx = session.getTransaction();
criteria = session.createCriteria(Archive.class);
criteria.add(Restrictions.eq("bagUuid", "4a90558c-4a5b-4af7-8c68-60ff81f74ef3"));
ScrollableResults items = criteria.scroll();
while ( items.next() ) {
Archive archive = (Archive)items.get(0);
archive.setDecision(1);
archive.setOperatorAssigned("test");
session.saveOrUpdate(archive);
session.flush();
session.clear();
}
tx.commit();
LOGGER.info("Archive Record is updated: "+archive.getFilePath());
}catch(Exception e){
recordUpdated = false;
tx.rollback();
LOGGER.error("Archive Record failed to update due to exception in updateArchiveRecord method: "+e.getMessage());
}
Here sometimes all records associated to UUID is updating but sometimes failing. I think it may be a issue with the Hibernate API. Does anybody else has faced the same issue.
Upvotes: 0
Views: 1199
Reputation: 1390
This line looks suspicious:
Archive archive = (Archive)items.get(0);
It means thart regardless of the number of items in the ScrollableResults, you will be updating only the first Archive object. If I understood what you are trying to do correctly, it should be a current record:
Archive archive = (Archive)items.get();
Also, I'd move out/delete session.flush() and session.clear(). The final code would look like this:
try{
session = sessionFactory.getCurrentSession();
tx = session.getTransaction();
criteria = session.createCriteria(Archive.class);
criteria.add(Restrictions.eq("bagUuid", "4a90558c-4a5b-4af7-8c68-60ff81f74ef3"));
ScrollableResults items = criteria.scroll();
while ( items.next() ) {
Archive archive = (Archive)items.get();
archive.setDecision(1);
archive.setOperatorAssigned("test");
session.saveOrUpdate(archive);
}
tx.commit();
session.close();
LOGGER.info("Archive Record is updated: "+archive.getFilePath());
}catch(Exception e){
recordUpdated = false;
tx.rollback();
LOGGER.error("Archive Record failed to update due to exception in updateArchiveRecord method: "+e.getMessage());
}
Slava Imeshev
Upvotes: 2