Bick
Bick

Reputation: 18511

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;
    } catch (HibernateException e) {
        session.getTransaction().rollback();
        savedSuccessfully = false;

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

Upvotes: 1

Views: 951

Answers (2)

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

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.

Upvotes: 3

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298818

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).

Upvotes: 1

Related Questions