How to remove delete objects from a joined table using JPA 2.1 CriteriaDelete

I want to remove (JPA 2.1) all “patients” from one “hospital”, but I ran into a problem: “UPDATE / DELETE query requests cannot determine joins”

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaDelete<PatientEntity> delete = cb.createCriteriaDelete(PatientEntity.class);
Root<PatientEntity> root = delete.from(PatientEntity.class);
Join<PatientEntity, HospitalEntity> join = root.join(PatientEntity_.Hospital);
delete.where(cb.equal(join.get(HospitalEntity_.id), id));
Query query = entityManager.createQuery(delete);
query.executeUpdate();

Error:

UPDATE/DELETE criteria queries cannot define joins

How to remove all patients while pooling is not possible?

+4
source share
1 answer

You can use a subquery that selects the correct entities and an "in" clause for this.

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaDelete<PatientEntity> delete = cb.createCriteriaDelete(PatientEntity.class);
Root<PatientEntity> root = delete.from(PatientEntity.class);


                Subquery<PatientEntity> subquery = delete.subquery(PatientEntity.class);
                Root<PatientEntity> root2 = subquery.from(PatientEntity.class);
                subquery.select(root2);
                /* below are narrowing criteria, based on root2*/   
                Join<PatientEntity, HospitalEntity> join = root2.join(PatientEntity_.Hospital);
                subquery.where(cb.equal(join.get(HospitalEntity_.id), id));


delete.where(root.in(subquery));
Query query = entityManager.createQuery(delete);
query.executeUpdate();
+3
source

Source: https://habr.com/ru/post/1529215/


All Articles