使用spring data jpa 心得

JpaSpecificationExecutor.findAll(new Specification<T>(){

   public Predicate toPredicate(Root<TabSgUserPackage> root, CriteriaQuery<?> query, CriteriaBuilder builder) {

}

})

最近一直使用springside 4 (spring data jpa(hibernate) + springMVC ) 今天遇到很是棘手的問題。 使用findAll 分頁的時候 java

若是調用root.fetch().....會報異常aused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list ........  select count(*) from .... spring

查一查百度緣由解釋是使用count 聚合函數不能調用fetch。 ide

要查詢指定的的對象,但owner沒有關聯目前選擇的集合或者對象。 函數

 而後看到這篇帖子 fetch

Paged findAll(…) with Specification does not work with join fetch

The way I've handled this is to use the CriteriaQuery.getResultType() method to check whether the query's projection is Long or the class the Specification is operating on. If the resultType is Long, the query is a count and no join fetches should be used. If the resultType is the class the Specification is operating on, it's a normal query and fetch joins can be used.

如上是一樓沙發的回答。  ui

判斷結果類型是不是long類型 來決定是否fetch
this

相關文章
相關標籤/搜索