Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Avoid StaleObjectStateException when deleting entity
- @Transactional
- public MyEntity getAndDelete(String prop) {
- List<MyEntity> list = (List<MyEntity>)sessionFactory
- .getCurrentSession()
- .createCriteria(MyEntity.class)
- .add( Restrictions.eq("prop", prop) )
- .list();
- // process the list, and find one entity
- MyEntity entity = findEntity(list);
- if (entity != null) {
- sessionFactory.getCurrentSession().delete(entity);
- }
- return entity;
- }
- @Transactional
- public MyEntity getAndDelete(String prop) {
- List<MyEntity> list = (List<MyEntity>)sessionFactory
- .getCurrentSession()
- .createCriteria(MyEntity.class)
- .add( Restrictions.eq("prop", prop) )
- .list();
- // process the list, and find one entity
- MyEntity entity = findEntity(list);
- if (entity != null) {
- // reload the entity with "select ...for update"
- // to ensure the exception is not thrown
- MyEntity locked = (MyEntity)sessionFactory
- .getCurrentSession()
- .load(MyEntity.class, entity.getId(), new LockOptions(LockMode.PESSIMISTIC_WRITE));
- if (locked != null) {
- sessionFactory.getCurrentSession().delete(locked);
- }
- }
- return entity;
- }
- @Transactional
- public MyEntity getAndDelete(String prop) {
- List<MyEntity> list = (List<MyEntity>)sessionFactory
- .getCurrentSession()
- .createCriteria(MyEntity.class)
- .add( Restrictions.eq("prop", prop) )
- .list();
- // process the list, and find one entity
- MyEntity entity = findEntity(list);
- if (entity != null) {
- // Remove the entity from the session.
- sessionFactory.getCurrentSession().evict(entity);
- // reload the entity with "select ...for update"
- MyEntity locked = (MyEntity)sessionFactory
- .getCurrentSession()
- .get(MyEntity.class, entity.getId(), new LockOptions(LockMode.PESSIMISTIC_WRITE));
- if (locked != null) {
- sessionFactory.getCurrentSession().delete(locked);
- }
- }
- return entity;
- }
Add Comment
Please, Sign In to add comment