Hibernate Session.delete() an object if exists

前端 未结 7 1742
谎友^
谎友^ 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: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();
            }
    
        }
    
    }
    

提交回复
热议问题