Hibernate使用Criteria分页关联查询去除重复
这里面role和user是多对多关系,比如一页显示15条数据,查询时查出来的user是15条,但是一旦有user对应多个role,这样显示的就没有15条数据了,在查询中单单加入
executableCriteria.setResultTransforme(Criteria.DISTINCT_ROOT_ENTITY);
这一句是不够的,这样只是查出15条数据,然后再去除重复的项,显示效果还是不对。
User类
@ManyToMany(fetch=FetchType.LAZY,cascade={CascadeType.PERSIST,
CascadeType.MERGE,CascadeType.REFRESH})
@JoinTable(name="system_user_role",joinColumns=@JoinColumn(name="user_id"),inverseJoinColumns=@JoinColumn(name="role_id"))
privateList<Role>roleList=newArrayList<Role>();
publicList<Role>getRoleList(){
returnroleList;
}
publicvoidsetRoleList(List<Role>roleList){
this.roleList=roleList;
}
action类中的方法
publicStringlist(){
CustomExample<User>example=newCustomExample<User>(this.getModel()){
privatestaticfinallongserialVersionUID=1L;
publicvoidappendCondition(Criteriacriteria){
entity.setValidFlag(ValidFlag.VALID);
criteria.addOrder(Order.asc("id"));List<Org>orgs2=orgService.findAllOrgByParentid(user.getParent().getId());
Long[]orgids2=newLong[orgs2.size()+1];
inti=0;
if(orgs2.size()>0){
for(Orgorg1:orgs2){
orgids2[i]=org1.getId();
i=i+1;
}
criteria.add(Restrictions.in("parent.id",orgids2));
}
orgs=orgs2;
if(getOrgId()!=null)
criteria.add(Restrictions.eq("parent.id",getOrgId()));
}
}
};
example.enableLike(MatchMode.ANYWHERE);
this.listResult=userService.findPageByExample(example,
PaginationSupport.pageToIndex(pageNum,numPerPage),numPerPage);
returnLIST;
}
底层findPageByExample方法
DetachedCriteriaexecutableCriteria1=DetachedCriteria.forClass(example.getEntityClass()).setFetchMode("roleList",FetchMode.SELECT);//将关联的rolelist集合对象采用查询方式抓取
executableCriteria=executableCriteria1.getExecutableCriteria(session);
executableCriteria=session.createCriteria(example
.getEntityClass());
executableCriteria.add(example);
example.appendCondition(executableCriteria);
inttotalCount=((Long)executableCriteria.setProjection(
Projections.rowCount()).uniqueResult()).intValue();
executableCriteria.setProjection(null);
executableCriteria
.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
for(inti=0;orders!=null&&i<orders.length;i++){
executableCriteria.addOrder(orders[i]);
}
executableCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);//去除重复项
Listitems=executableCriteria.setFirstResult(startIndex)
.setMaxResults(pageSize).list();
PaginationSupportps=newPaginationSupport(items,totalCount,
startIndex,pageSize);
returnps;
将关联的rolelist集合对象采用查询方式抓取
用这种方式取出的才是正确的数据