user8681
user8681

Reputation:

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.

Upvotes: 9

Views: 19527

Answers (2)

Cruis
Cruis

Reputation: 377

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

Upvotes: 10

guardian
guardian

Reputation: 439

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));

Upvotes: 24

Related Questions