Guest User

Untitled

a guest
Aug 19th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. Avoid StaleObjectStateException when deleting entity
  2. @Transactional
  3. public MyEntity getAndDelete(String prop) {
  4. List<MyEntity> list = (List<MyEntity>)sessionFactory
  5. .getCurrentSession()
  6. .createCriteria(MyEntity.class)
  7. .add( Restrictions.eq("prop", prop) )
  8. .list();
  9.  
  10. // process the list, and find one entity
  11. MyEntity entity = findEntity(list);
  12. if (entity != null) {
  13. sessionFactory.getCurrentSession().delete(entity);
  14. }
  15. return entity;
  16. }
  17.  
  18. @Transactional
  19. public MyEntity getAndDelete(String prop) {
  20. List<MyEntity> list = (List<MyEntity>)sessionFactory
  21. .getCurrentSession()
  22. .createCriteria(MyEntity.class)
  23. .add( Restrictions.eq("prop", prop) )
  24. .list();
  25.  
  26. // process the list, and find one entity
  27. MyEntity entity = findEntity(list);
  28. if (entity != null) {
  29. // reload the entity with "select ...for update"
  30. // to ensure the exception is not thrown
  31. MyEntity locked = (MyEntity)sessionFactory
  32. .getCurrentSession()
  33. .load(MyEntity.class, entity.getId(), new LockOptions(LockMode.PESSIMISTIC_WRITE));
  34. if (locked != null) {
  35. sessionFactory.getCurrentSession().delete(locked);
  36. }
  37. }
  38. return entity;
  39. }
  40.  
  41. @Transactional
  42. public MyEntity getAndDelete(String prop) {
  43. List<MyEntity> list = (List<MyEntity>)sessionFactory
  44. .getCurrentSession()
  45. .createCriteria(MyEntity.class)
  46. .add( Restrictions.eq("prop", prop) )
  47. .list();
  48.  
  49. // process the list, and find one entity
  50. MyEntity entity = findEntity(list);
  51. if (entity != null) {
  52.  
  53. // Remove the entity from the session.
  54. sessionFactory.getCurrentSession().evict(entity);
  55.  
  56. // reload the entity with "select ...for update"
  57. MyEntity locked = (MyEntity)sessionFactory
  58. .getCurrentSession()
  59. .get(MyEntity.class, entity.getId(), new LockOptions(LockMode.PESSIMISTIC_WRITE));
  60. if (locked != null) {
  61. sessionFactory.getCurrentSession().delete(locked);
  62. }
  63. }
  64. return entity;
  65. }
Add Comment
Please, Sign In to add comment