How to delete entities from a joined table with JPA 2.1 CriteriaDelete
Asked Answered
T

1

7

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?

Transfinite answered 27/2, 2014 at 13:38 Comment(2)
Use JPA queries instead due to it is type safe which is not so complex as criteria...Davide
This is not the answer, asking the OP to use the other way around techniques, despite providing solution to actual question.Cuirass
K
8

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();
Knoxville answered 4/1, 2016 at 14:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.