4

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;

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

0

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

1 Comment

Because it’s inefficient to load something from the DB into memory just to delete it. Sometimes that does not matter much, sometimes it makes all the difference.
0

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

See Batch processing

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.