Search code examples
javaperformancehibernateoptimizationspring-orm

How to delete entities using Criterion efficiently?


Currently, I have to create a temporary Criteria and get the matching entity list using Criteria.list(), and then, pass the list to HibernateTemplate.deleteAll():

void delete(Criterion criterion) {
    Criteria c = DetachedCriteria.forClass(Foo.class).getExecutableCriteria(session);
    c.add(criterion);
    getHibernateTtemplate().deleteAll(c.list());
}

Is it possible to delete by Criterion but without load the list at the first?

Maybe, I should convert the criterion to HQL like "delete from Foo where " + criterion.toHQL()?

BACKGROUNDS

I have a search form which later be parsed and converted into a Criteria composition.

The search results are retrieved by using Criteria.list().

Now, a question came into the sight, I want to delete all the search results. Should I parse the search form again but in different manner to convert it into an HQL string? If I can reuse the Criteria, things would be simpler.

As the Criteria is most equivalent to WHERE clause, (isn't it?) I see no reason a Criteria couldn't be used for deletion.


Solution

  • You indeed only can do this using HQL. There is no criteria API equivalent.