9

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.

Hash
  • 4,647
  • 5
  • 21
  • 39
Jorn
  • 20,612
  • 18
  • 79
  • 126

2 Answers2

23

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));
guardian
  • 429
  • 3
  • 5
8

in JPA 2.1, there are Criteria APIs exactly as what you want.it looks like this:

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

Cruis
  • 357
  • 2
  • 9