解决JPA使用root.fetch时报the owner of the fetched association was not present in the select list 问题

旧街凉风 提交于 2020-03-02 18:38:28

在使用JPA Specification 进行多条件查询时,使用root.fetch("xx")关联查询LAZY的属性时,会报如下错误:

org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list

 原因是由于查询时候除了执行select xxx from A 之外,还执行了select count(*) from A,而select count是不能调用fetch的,所以我们可以根据查询结果的类型来判断是否进行fetch,如果是long类型,则不执行fetch操作;

解决方法如下:

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

   public Predicate toPredicate(Root<TabSgUserPackage> root, CriteriaQuery<> query, CriteriaBuilder builder) {  
        if (!query.getResultType().equals(Long.class)) {
            root.fetch("xxx", JoinType.LEFT);
        }
    }
  
})  

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!