Alex Rivera | Logout

Hibernate Session.delete() an object if exists

Asked 2011-04-25T07:08:12.137
19

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:

  1. 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?
  2. 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?

Edit
Report

1 Answer

1

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 you know the identifier of the object you want to delete, then you can create an instance with its identifier set and pass it to session delete method. This instance would be considered to be in detached state ( since there is an identifier associated), however it will be internally reattached to session by Hibernate and then deleted.

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?

The delete method will throw StaleObjectException if it cannot find the object to be deleted. So you can use exception handling to decide what to do in that case.

answered 2012-09-10T10:44:40.980

Your Answer