简体   繁体   中英

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.

I think that you can use method execute(HibernateCallback action) from class HibernateTemplate . It could look like this:

final Criterion criteria;
HibernateTemplate template;
template.execute(new HibernateCallback() {
    @Override
    public Object doInHibernate(Session session) throws HibernateException, SQLException {
        List toDelete = session.createCriteria(Student.class).add(criteria).list();
        for (Object o: toDelete){
            session.delete(o);
        }
    }
});

IMHO this solution is not very efficient, because you must read all entries before you remove them. What is more you must remove each entry individually, which is very unefficient.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM