Hibernate Session.delete() an object if exists
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 开发者_JAVA技巧the receiving Session or a transient instance with an identifier associated with existing persistent state.
My questions are:
- 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 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?
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
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();
}
}
}
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;
}
Just found one better solution:
Query q = session.createQuery("delete Entity where id = X");
q.executeUpdate();
Hibernate Delete query
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.
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();
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();
精彩评论