1、从redis按照顺序查询出推荐群组(id),然后通过in查询数据库得到群组的详细信息,并按照in的顺序返回
/**
* 获取推荐群列表
* @return
*/
public List<Groups> selectTopGroups() {
CacheManager cm=CacheManager.getInstance();
Set<String> s=cm.getZSetMembers(KeyParam.RECOMMEND_GROUP);
logger.debug("推荐列表" + s);
List<Integer> groupIds = null;
if(s!=null && s.size() > 0){
groupIds = new ArrayList<Integer>();
for(String g : s){
try {
Integer gId = Integer.parseInt(g);
groupIds.add(gId);
} catch (Exception e) {
}
}
}
if(groupIds != null && groupIds.size() > 0){
Map<String, Object> paramMap = new HashMap<String, Object>();
StringBuilder sortStr = new StringBuilder();
for(Integer id : groupIds){
sortStr.append(id).append(",");
}
sortStr.delete(sortStr.lastIndexOf(","), sortStr.length());
paramMap.put("groupIdList", groupIds);
paramMap.put("sortStr", sortStr.toString());
return this.mapperFactory.groupsMapper.selectGroupListBySort(paramMap);
}
return null;
}
mapper.java/**
* 根据群id获取群的全部信息,按照list里面的序号排序
* @param paramMap 参数map <br/>
* groupIdList --- List<Integer> <br/>
* sortStr ---- String 排序字符串,格式:'1932,2342,3242' 也就是集合中的id,已逗号隔开
*/
List<Groups> selectGroupListBySort(Map<String, Object> paramMap);
mapper.xml<!-- 根据群id获取群的全部信息,按照list里面的序号排序 -->
<select id="selectGroupListBySort" resultMap="BaseResultMap" parameterType="java.util.Map" >
select
<include refid="Base_Column_List" />
from groups
where id in
<foreach collection="groupIdList" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
order by find_in_set(id, #{sortStr,jdbcType=VARCHAR}) asc;
</select>
SQL基础:
--按照in的顺序查询
--这种有bug
select u.id,u.name,u.sex,u.photo,instr('4,7,17,20,5,6',u.id) as i from user u where u.id in (4,7,17,20,5,6) order by i asc;
--bug案例
select u.id,u.name,u.sex,u.photo,instr('11,1,111',u.id) as i from user u where u.id in (11,1,111) order by i asc; --instr函数的含义就是找u.id在前面'11,1,111'的索引,于是这种就会有bug
--bug改进方案(然并卵)
select u.id,u.name,u.sex,u.photo from user u where u.id in (11,1,111) order by instr(',11,1,111,' , ','+u.id+',') asc;
--最好的方案
select u.id,u.name,u.sex,u.photo from user u where u.id in (11,1,111) order by find_in_set(u.id,'11,1,111') asc;
--普通查询(会默认按照id排序)
select u.id,u.name,u.sex,u.photo from user u where u.id in (4,7,17,20,5,6);