使用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

相关文章
相关标签/搜索