Bick
Bick

Reputation: 18511

Hibernate - how to delete with condition without loading to memory?

I have an object -

 @Entity
 public class myObject{
      public string fieldA;
      public string fieldB
      ...
 }

I don't have any instance of it but I want to delete all the rows in db that have fieldA == A.

Is this the correct way ?

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

        session.getTransaction().commit();
        savedSuccessfully = true;
    } catch (HibernateException e) {
        session.getTransaction().rollback();
        savedSuccessfully = false;

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

Upvotes: 4

Views: 3565

Answers (4)

Gordian Yuan
Gordian Yuan

Reputation: 5040

To execute an HQL DELETE, use the Query.executeUpdate() method

See Batch processing

Upvotes: 0

user591593
user591593

Reputation:

why would you do that if you have decided to implement using ORM ?

The correct procedure to delete something under ORM implemented application would be:

  1. get the object with the related fieldA and fieldB
  2. delete the object

Upvotes: 0

Lawrence McAlpin
Lawrence McAlpin

Reputation: 2785

Yes, to do a batch delete without first having to query the data, you would use HQL:

session.createQuery("delete from MyClass where ...").executeUpdate();

Upvotes: 0

Michael J. Lee
Michael J. Lee

Reputation: 12406

Take a look at using native sql in hibernate and the session.createSQLQuery to make sure hibernate doesn't get involved with wiring beans with HSQL.

Also avoid using String concatenation to build your queries. Lastly, your database will most like be your bottle neck with a simple query like this so make sure you have proper indexes on the table.

Upvotes: 2

Related Questions