Hibernate Session.delete() an object if exists

前端 未结 7 1740
谎友^
谎友^ 2020-12-31 03:41

In JavaDoc of Session class the description of delete method is:

Remove a persistent instance from the datastore. The argument may be

相关标签:
7条回答
  • 2020-12-31 04:01

    Just found one better solution:

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

    Hibernate Delete query

    0 讨论(0)
  • 2020-12-31 04:02

    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
    
    0 讨论(0)
  • 2020-12-31 04:11

    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.

    0 讨论(0)
  • 2020-12-31 04:15

    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();
    
    0 讨论(0)
  • 2020-12-31 04:18

    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;
    }
    
    0 讨论(0)
  • 2020-12-31 04:21
    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();
            }
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题