I want to delete (JPA 2.1) all patients
from one Hospital
, but run into a problem:
UPDATE/DELETE criteria queries cannot define 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 should I delete all Patients, while the Join cannot be performed?
You can use a subquery that selects proper entities and 'in' clause for that.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With