JPA CriteriaBuilder子查詢方式
JPA CriteriaBuilder子查詢
給自己做個備忘
/** 檢索關鍵字 */ if (keyWord != null && !keyWord.trim().equals("")) { // 創建子查詢對象 Subquery<Store> subquery = criteriaQuery.subquery(Store.class); Root<Store> root2 = subquery.from(Store.class); subquery.select(root2.<Store> get("id")); subquery.where(criteriaBuilder.like(root2.<String> get("name"), "%" + keyWord + "%")); // 給讀者稍微解釋一下,也給自己留個記憶 // 這裡的意圖是將關鍵做兩個模糊檢索,一個是在本表中檢索title字段 // 就是criteriaBuilder.like(root.<String> get("title"), "%" + keyWord + "%") // 二是將字段與子表中的檢索出來的id與本表中store字段做匹配 // criteriaBuilder.in(root.get("store")).value(subquery)) // 至於id怎麼檢索出來的,用子查詢模糊檢索出來的,參照上面的子查詢 restrictions = criteriaBuilder.and(restrictions,criteriaBuilder.or(criteriaBuilder.like(root.<String> get("title"), "%" + keyWord + "%"),criteriaBuilder.in(root.get("store")).value(subquery))); }
Jpa 在CriteriaBuilder中添加where條件NotIn子查詢
final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery<Person> cq = cb.createQuery(Person.class); final Root<Person> root = cq.from(Person.class); cq.select(root); final Subquery<Integer> subquery = cq.subquery(Integer.class); final Root<Person> validityIDSQ = subquery.from(Person.class); subquery.select(cb.max(validityIDSQ.get(Person_.validityID))); subquery.groupBy(validityIDSQ.get(Person_.personID)); cq.where(cb.in(root.get(Person_.validityID)).value(subquery)); // 將生成 select person0_.id as id1_0_, person0_.personID as personID2_0_, person0_.validityID as validity3_0_, person0_.value as value4_0_ from person person0_ where person0_.validityID in ( select max(person1_.validityID) from person person1_ group by person1_.personID)
自身所需NotIn語法,所以是
Subquery<String> manageUserSubquery = query.subquery(String.class); Root<RelationUserManagePlateDomain> relationUserManagePlateDomainRoot = manageUserSubquery.from(RelationUserManagePlateDomain.class); Join<RelationUserManagePlateDomain, UserDomain> relationUserManagePlateDomainUserDomainJoin = relationUserManagePlateDomainRoot.join(RelationUserManagePlateDomain_.user, JoinType.INNER); Subquery<String> subquery = manageUserSubquery.select(relationUserManagePlateDomainUserDomainJoin.get(UserDomain_.id)); Predicate predicate1 = criteriaBuilder.and(criteriaBuilder.not(criteriaBuilder.in(root.get(UserDomain_.id)).value(manageUserSubquery))); predicate.getExpressions().add(predicate1);
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。
推薦閱讀:
- jpa EntityManager 復雜查詢實例
- 使用Spring Data Jpa查詢全部並排序
- SpringDataJPA詳解增刪改查操作方法
- 全面解析JPA 倉庫repository中的findAll()方法
- Spring Data JPA中 in 條件參數的傳遞方式