Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete multiple objects at once using CriteriaBuilder

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 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?

I can of course execute the select, then call entityManager.remove(object) for each result, but that feels very inefficient.

like image 393
Jorn Avatar asked Aug 06 '14 09:08

Jorn


1 Answers

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:

query.where(criteriaBuilder.lessThanOrEqualTo(root.get("id"), someId));
like image 61
guardian Avatar answered Oct 14 '22 15:10

guardian