java 使用 CriteriaBuilder 一次删除多个对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25156510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete multiple objects at once using CriteriaBuilder
提问by Jorn
I'm trying to delete a bunch of objects with one query using the CriteriaBuilder
API. I'm looking for something like this select:
我正在尝试使用CriteriaBuilder
API通过一个查询删除一堆对象。我正在寻找这样的选择:
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<T> query = criteriaBuilder.createQuery(entityClass);
Root<T> root = query.from(entityClass);
query.select(root).where(/*some condition*/);
return entityManager.createQuery(query).getResultList();
but then a delete instead of a select. As far as I can see, there's no remove
or delete
method on CriteriaQuery
. Is it possible using this API?
但随后是删除而不是选择。据我所知, 上没有remove
ordelete
方法CriteriaQuery
。是否可以使用此 API?
I can of course execute the select, then call entityManager.remove(object)
for each result, but that feels very inefficient.
我当然可以执行选择,然后调用entityManager.remove(object)
每个结果,但这感觉效率很低。
回答by guardian
Try this:
试试这个:
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaDelete<SomeClass> query = criteriaBuilder.createCriteriaDelete(SomeClass.class);
Root<SomeClass> root = query.from(SomeClass.class);
query.where(root.get("id").in(listWithIds));
int result = entityManager.createQuery(query).executeUpdate();
The where clause can laso look like this:
where 子句可以看起来像这样:
query.where(criteriaBuilder.lessThanOrEqualTo(root.get("id"), someId));
回答by Cruis
in JPA 2.1, there are Criteria APIs exactly as what you want.it looks like this:
在 JPA 2.1 中,有你想要的标准 API。它看起来像这样:
CriteriaBuilder cBuilder = em.getCriteriaBuilder();
CriteriaDelete<T> cq = cBuilder.createCriteriaDelete(entityClass);
Root<T> root = cq.from(entityClass);
cq.where(/*some codition*/);
int result = em.createQuery(cq).executeUpdate();
you can refert to JPA 2.1 SPEC and API here
您可以在此处参考JPA 2.1 SPEC 和 API