In JavaDoc of Session class the description of delete method is:
Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving Session or a transient instance with an identifier associated with existing persistent state.
My questions are:
- I want to delete a detach object, can I use this method, AFAIK session first makes an object persistent from detach and then perform its operation. Am I right?
- If I am not sure about the existence of the object in database, should I use Session.get() to check the whether or not it is null and then perform delete operation or I can use directly delete operation?
Here is a code snippet:
public void removeUnallocatedUserIfExits(final long itemId) {
getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
session.flush();
session.setCacheMode(CacheMode.IGNORE);
UnallocatedUser unallocatedUser;
if ((unallocatedUser = (UnallocatedUser) session.get(UnallocatedUser.class, itemId)) != null) {
session.delete(unallocatedUser);
}
session.flush();
return null;
}
});
}
Is the okay?
This means you can directly pass your
entitytosession.delete(), in order to delete that object. Further, you need not check whether the entity exist or not. There should be an exception if no record found in the database. In fact, we usually don’t really get this case. We always delete an existing entity, I mean usual logic is like that; so, no need to do that. You can simply do this,or you can do this instead,
Btw, you can also use this version
session.delete(String query),