Consider this example: (User is a class with two fields: a generated id and username)
User user = new User();
user.setUserName("username");
SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
session.save(user);
user = null; // Does this deletes the object?
session.getTransaction().commit();
session.close();
Because user is persistent object, why setting it to null doesn’t removes the object from DB?
No, it doesn’t. Setting a local variable to
nullmeans nothing outside the method. Hibernate cannot know you’ve nullified your local variable (even if it was a field not managed by hibernate, it would still be impossible for hibernate to detect change).The reason is that variables and fields are simply references to objects, not the objects themselves. So when you null a reference, this doesn’t mean the object ceases to exist. It still exists in the hibernate session in this case. (As JB Nizet noted, if the object owning the field is managed by hibernate, hibernate can detect the change and delete the object, but that is only true for hibernate-managed objects: attached entities)
You need to call
session.delete(user)