使用spring data jpa 心得

[java]  view plain copy
  1. JpaSpecificationExecutor.findAll(new Specification<T>(){  
  2.   
  3.    public Predicate toPredicate(Root<TabSgUserPackage> root, CriteriaQuery<?> query, CriteriaBuilder builder) {  
  4.   
  5. }  
  6.   
  7. })  

最近一直使用springside 4 (spring data jpa(hibernate) + springMVC ) 今天遇到非常棘手的问题。 使用findAll 分页的时候

如果调用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 ....

查一查百度原因解释是使用count 聚合函数不能调用fetch。

要查询指定的的对象,但owner没有关联目前选择的集合或者对象。

 然后看到这篇帖子

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.

如上是一楼沙发的回答。 

判断结果类型是否是long类型 来决定是否fetch

你可能感兴趣的:(使用spring data jpa 心得)