开发者

hibernate - how to do a conditional delete without loading to memory

I have an object -

 @Entity
 public class myObject{
      public MySecondObject objA;
      public MySecondObject objB;
      ...
 }

I dont have any instance of it but I want to delete all the rows in db that have fieldA == thirdObj I have an instance of thirdOBJ but no instance of myobjects. it is possible to do it with native sql. but than I will need to use the auto assigned id of thirdobj - to compare in the db.

Is there a more elegant way than this?

    try {
        session.beginTransaction();
        session.createQuery("delete from MyObject where fieldA = " +        
                             thirdObject.getID()).executeUpdate();

        session.getTransaction().commit();
        savedSuccessfully = true;
  开发者_Python百科  } catch (HibernateException e) {
        session.getTransaction().rollback();
        savedSuccessfully = false;

    } finally {
        session.close();
    }
    return savedSuccessfully;


It should work with HQL

session
  .createQuery("delete from MyObject where objA = :third")
  .setEntity("third", thirdObject)
  .executeUpdate();

But there are some limits: HQL deletes do not cascade (most) references and do not recognize the real type if there are subclasses. If your class is a simply class, it will work fine.


a) In your example, you are using HQL, not native SQL. Big difference.
b) No, those are the two possibilities. Delete an Object (but you have to load it first) or delete by id (but that's only possible through HQL or native SQL).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜