2014-02-27 150 views
4

我想刪除(JPA 2.1)所有的「患者」,從一個「醫院」,但碰到一個問題: 「UPDATE/DELETE標準查詢不能定義連接」如何刪除刪除連接表實體JPA 2.1 CriteriaDelete

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

使用JPA的查詢,而不是因爲它是類型安全的這是不一樣的標準很複雜... – user3252538

+0

這也不是辦法,要求OP使用技巧周圍的其他方式,儘管實際問題提供解決方案。 – srk

回答

3

您可以使用選擇「在」條款適當的實體和一個子查詢。

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();