Search code examples
javadatabasehibernatejersey

Hibernate 5 Deleting Entity By Id Not Working Reliably


I am currently working on the delete operation of a REST API made with Jersey 3.0.3 . I use Hibernate 5.6.2 and am new to Hibernate, but after some research, trial and error I settled on the code below with the following problem: when trying to delete an object by id (the object contains only String, int, long and enum values as attributes) the deletion executes without an error, but does not work reliably. Generally, when trying to delete a recently added object the deletion has to be executed exactly twice to work. In all other cases deletion works fine.

I have tried differents methods for deleting the object (like session.remove(obj), session.delete(obj) and also tried deleting using a query), but every approach leads to the same unexpected behavior.

What am I doing wrong?

Code for saving CustomObject obj:

Session session = sessionFactory.openSession();
session.beginTransaction();
Serializable s = session.save(obj);
session.getTransaction().commit();
session.close();

Code for deleting CustomObject obj by id:

Session session = sessionFactory.openSession();
session.beginTransaction();
CustomObject obj = session.get(CustomObject.class, id);
session.getTransaction().commit();

session.beginTransaction();
if (obj != null) {
     session.delete(obj);
}
session.getTransaction().commit();
session.close();

Solution

  • I am not quite sure why this fixed it, but I changed my code for saving the object from session.save(obj) to session.saveOrUpdate(obj) and everything works fine now.