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?

7 Answers 7

30

or a transient instance with an identifier associated with existing persistent state

This means you can directly pass your entity to session.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,

SomeEntity ent = session.load(SomeEntity.class, '1234');
session.delete(ent);

or you can do this instead,

SomeEntity ent = new SomeEntity('1234'); // used constructor for brevity
session.delete(ent);

Btw, you can also use this version session.delete(String query),

sess.delete("from Employee e where e.id = '1234'"); // Just found it is deprecated
Sign up to request clarification or add additional context in comments.

2 Comments

You should use session.load() instead of .get() to avoid fetching the entity's data.
@GuillaumeF., Yes, then you might get a proxied instance. Furthermore, the doc states, "You should not use load() to determine if an instance exists (use get() instead). Use load() only to retrieve an instance that you assume exists, where non-existence would be an actual error". Here we're assuming that the entity exists; so, yes, load() would be of choice.
6
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class DeletePersistentObjectWithHibernate {

public static void main(String[] args) {

        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

        Session session = sessionFactory.getCurrentSession();

        long id = 2;

        try {
            session.beginTransaction();

            Employee employee = (Employee) session.get(Employee.class, id);

            session.delete(employee);

            session.getTransaction().commit();
        }
        catch (HibernateException e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        }

    }

}

2 Comments

Please add some comment
session.get() will fetch Employee object from database. if Employee object contain another object then that object will also fetch at same time and then Employee will be deleted from the database by session.delete(obj)
4

Try this...

public <T> T delete(T t) throws Exception {
    try {
        t = load(t);
        session.delete(t);
        session.flush();
    } catch (Exception e) {
        throw e;
    } finally {
        session.clear();
    }

    return t;
}

public <T> T load(T t) {
    session.buildLockRequest(LockOptions.NONE).lock(t);
    return t;
}

Comments

4

Just found one better solution:

Query q = session.createQuery("delete Entity where id = X");
q.executeUpdate();

Hibernate Delete query

Comments

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.

Comments

1

You can easily achieve by following simple hibernate as follows,

Session session=getSession();  
String hql = "delete from Student where classId= :id"; 
session.createQuery(hql).setString("id", new Integer(id)).executeUpdate();

Comments

0

Hibernate native query sample as follows.

import org.hibernate.query.nativeQuery;  

String sql = "Delete from Student where classId= :id"; 
NativeQuery query = session.createNativeQuery(sql.toString()); 
query.executeUpdate();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.