Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

join

jpa

criteria

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?

like image 990
Dimitri Dewaele Avatar asked Feb 27 '14 13:02

Dimitri Dewaele


1 Answers

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();
like image 173
vinga Avatar answered Oct 22 '22 10:10

vinga