Hibernate Session.delete() an object if exists
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
Just found one better solution:
Query q = session.createQuery("delete Entity where id = X");
q.executeUpdate();
Hibernate Delete query
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;
}
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();
}
}
}