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 save开发者_运维问答dSuccessfully;
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.
Yes, to do a batch delete without first having to query the data, you would use HQL:
session.createQuery("delete from MyClass where ...").executeUpdate();
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:
- get the object with the related fieldA and fieldB
- delete the object
To execute an HQL DELETE, use the Query.executeUpdate() method
See Batch processing
精彩评论