query specified join fetching, but the owner of the fetched association was not present in the select list

报标题的错误,是因为在 select count的时候,不需要fetch

所以在取完count以后,再把fetch加进去,变成left join  fetch

 

/**
* 请把jhql以o为返回对象,例如“from user o where”
*
* @param jhql
* @param pageSize
* @param page
* @return
*/
public <T> Page<T> getPageListByJHQL(String jhql, int pageSize, int page) {
StringBuffer countHql = new StringBuffer("select count(o) ");
StringBuffer singleHql = new StringBuffer("select o ");
Query countQuery = em.createQuery(countHql.append(jhql).toString());

long count = (Long) countQuery.getSingleResult();

if (count == 0)
return null;

int index = (page - 1) * pageSize;

Query query = em.createQuery(singleHql.append(
jhql.replace("left join", "left join fetch")).toString());

List<T> list = query.setMaxResults(pageSize).setFirstResult(index)
.getResultList();

em.clear(); // 分离内存中受EntityManager管理的实体bean,让VM进行垃圾回收

PageRequest pageRequest = new PageRequest(page, pageSize);

Page<T> pageList = new PageImpl<T>(list, pageRequest, count);
return pageList;
}

posted @ 2016-01-15 21:09  clarkapp  阅读(2230)  评论(0编辑  收藏  举报