在使用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);
}
}
})