简体   繁体   English

如何有效使用Criterion删除实体?

[英]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() : 当前,我必须创建一个临时Criteria并使用Criteria.list()获取匹配的实体列表,然后将该列表传递给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? 是否可以通过Criterion删除但不首先加载列表?

Maybe, I should convert the criterion to HQL like "delete from Foo where " + criterion.toHQL() ? 也许,我应该将条件转换为HQL,例如"delete from Foo where " + criterion.toHQL()

BACKGROUNDS 背景资料

I have a search form which later be parsed and converted into a Criteria composition. 我有一个搜索表单,稍后将其解析并转换为Criteria组成。

The search results are retrieved by using Criteria.list(). 通过使用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? 我是否应该以另一种方式再次解析搜索表单以将其转换为HQL字符串? 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. 由于条件最等同于WHERE子句,(不是吗?)我认为没有理由不能将条件用于删除。

I think that you can use method execute(HibernateCallback action) from class HibernateTemplate . 我认为您可以使用类HibernateTemplate中的 execute(HibernateCallback action)方法。 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. 您确实只能使用HQL做到这一点。 There is no criteria API equivalent. 没有等效的标准API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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