首页 / 操作系统 / Linux / MyBatis 实现消息页面,批量查询用户信息
1,背景
开发了Java这么久,有的时候会偷懒写一些代码,影响性能。 比如 消息列表里面,查询用户信息。 这样就会造成一个N+1的问题,有多少条消息就查询了多少次用户信息。hibernate 里面有个很不错的功能 left outer join fetch。可以解决N+1的问题,但是现在已经没有人用hibernate了,用mybatis的人比较多,所以得手动写代码进行查询优化了。开始写代码想着完成功能,在后来就要考虑优化,使用高效的查询方式,这样的才能提高用户体验。2,MyBatis批量查询
比如数据表为:<select id="selectByIdBatch" parameterType="java.util.List" resultMap="userInfo">SELECTid,name,sex,phoneFROMuser_info<where>id in<foreach item="id" collection="list" separator="," open="(" close=")" index="">#{id, jdbcType=NUMERIC}</foreach></where></select>然后使用在循环里面,找到多个id,然后用in查询将user_info数据查询出来,在放到msg的对象里面。比如两个类public class Message{private Long id;private String content;private Date createTime;private Long uid;priavte UserInfo userInfo;}public class UserInfo{private Long id;private String name;private String phone;}//示意代码:用作代码展示,没有编译过。List<Message> msgList = msgMapper.selectPage(0,10);//示意Set存储,保证Id不重复。Set<Long> msgIds = new HashSet<Long>();//循环Message消息,找到所有Id。for(Message msg:msgList){if(msg != null && msg.getId() != null){msgIds.add(msg.getId());}}//批量查询用户信息。List<UserInfo> userList = userMapper.selectByIdBatch(new ArrayList<Long>(msgIds));//将用户List转换成MapMap<Long,List<UserInfo>> userMap = new HashMap<Long,List<UserInfo>>();for(UserInfo userInfo:userList){if(userInfo != null && userInfo.getId() != null){//转换map。userMap.add(userInfo.getId(),userInfo);}}//循环消息再把UserInfo对象放回去。for(Message msg : msgList){if(msg != null && msg.getUid() != null){UserInfo userInfo = userMap.get(msg.getUid());//设置用户msg.setUserInfo(userInfo);}}//最后再显示。.....3,总结
虽然代码写的比较多,但是性能得到了提供,查询数据库的次数减少了。
优化了查询效率,提高了用户体验,减少了用户等待时间。
这里有个小技巧,mybatis不支持Set,只能用List。Set保持id不重复。
使用new ArrayList(msgIds) 可以将Set转换成List。
查询完成之后放到Map数组里面,减少循环次数。
这样就完成优化了,效率得到了提高。MyBatis入门学习教程 http://www.linuxidc.com/Linux/2015-02/113771.htmJava实战应用:Mybatis实现单表的增删改 http://www.linuxidc.com/Linux/2014-06/103456.htm[Java][Mybatis]物理分页实现 http://www.linuxidc.com/Linux/2014-04/99889.htmMybatis快速入门教程 http://www.linuxidc.com/Linux/2013-06/85762.htmMybatis的关于批量数据操作的测试 http://www.linuxidc.com/Linux/2012-05/60863.htmMybatis中对List<Object> 对象List的批处理插入操作 http://www.linuxidc.com/Linux/2014-02/96916.htmMyBatis 的详细介绍:请点这里
MyBatis 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-04/130597.htm<!-- Baidu Button BEGIN -->