我想从一个“医院”中删除( JPA 2.1 )所有“患者”,但遇到问题: “UPDATE / DELETE条件查询无法定义连接”
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();
错误: 的
UPDATE/DELETE criteria queries cannot define joins
如何删除所有患者,而无法执行加入?
答案 0 :(得分:3)
您可以使用选择正确实体的子查询和&#39;条款。
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();