【Java】记录一次代码优化
最近几天闲下来,主动把之前的代码优化了一下:)

原处理
String eventId = "";
String aTime = "";
for (UserEvent event : userEventList) {
eventId = event.getEventId(); // 获取业务B信息
List<EntityB> listB = mapperB.selectBInfoByEventId(eventId);
event.setListB(listB); // 获取业务C信息
List<EntityC> listC = mapperC.selectCInfoByEventId(eventId);
event.setListC(listC); // 查看是否有业务B处理
EntityB entityB = mapperB.selectBInfoByPrimary(phone, eventId);
event.setIsActionB(null == entityB ? "false" : "true"); // 获取业务A和用户信息
User userInfo = mapperA.selectEventUserInfoByEventId(eventId);
if(null != userInfo){
aTime = userInfo.getTime();
event.setTime(aTime == null ? "" : sdfMd.format(sdfYmd.parse(aTime)));
event.setUserInfo(userInfo);
}
}
<select id="selectBInfoByEventId" parameterType="String" resultType="EntityA">
SELECT
B.phone AS phone,
B.time AS time,
U.name AS userName
FROM table_b B
LEFT JOIN user U ON U.phone = B.phone
WHERE B.event_id = #{eventId}
ORDER BY B.time ASC
</select>
<select id="selectCInfoByEventId" parameterType="String" resultType="EntityC">
SELECT
C.cmtId,
C.referId,
C.time,
U.name AS userName
( SELECT TU.name FROM table_c TC
LEFT JOIN user TU ON TU.phone = TC.phone
WHERE TC.cmt_id = TC.refer_id
) AS referName
FROM table_c C
LEFT JOIN user U ON C.phone = U.phone
WHERE C.event_id = #{eventId}
ORDER BY C.time ASC
<select id="selectEventUserInfoByEventId" parameterType="java.lang.String" resultType="User">
SELECT
U.name,
U.picId,
A.time
FROM table_a A
LEFT JOIN user U ON U.phone = A.phone
WHERE A.event_id = #{eventId}
</select>
优化分析
- 在代码结构上,要避免在for循环中作查询处理。考虑将查询参数evenId从for循环中提取出来,做批量查询,然后再将查询结果设定到对应的实体类中。
- 在业务上,对于每一个UserEvent中的eventId,业务表A中必定对应有一条记录,而在业务表B和业务表C中则未必有与这个eventId关联的数据。因此,可以将业务表A作为主表,通过eventId与另外几个表关联查询。查询次数也由原来的至少四次减少为一次查询。
- 对于联合查询的结果,以UserEvent作为查询结果的实体类,使用Mybatis中的collection、association来处理结果映射。
- 另外,各业务表的查询中都有与用户表User的关联,考虑将各业务信息的查询处理创建为视图。这样不仅能简化联合查询中SQL语句,也可以隔离基础表的数据。
优化后的代码
int eventSize = userEventList.size();
List<String> eventIds = new ArrayList<String>();
// 如果考虑去掉重复数据,可以使用集合Set,但是作为Mybatis的输入参数,最后还是需要将Set转化为List。
// 此处直接使用List,因为在业务上排除了重复数据的可能性。
for (int i = 0; i < eventSize; i++) {
eventIds.add(userEventList.get(i).getEventId());
}
Map<String, Object> paramsMap = new HashMap<String, Object>();
paramsMap.put("eventIds", eventIds);
paramsMap.put("phone", phone);
List<UserEvent> eventInfoList = eventMapper.selectUserEventInfo(paramsMap); // 将查询结果转化为Map存储,方便调用
Map<String, UserEvent> eventInfoMap = new HashMap<String, UserEvent>();
for(UserEvent event : eventInfoList){
eventInfoMap.put(event.getEventId(), event);
}
UserEvent newEvent = null;
String aTime = null;
for(UserEvent event : roadEventList){ // 从查询结果Map中取出补充信息,保存到原UserEvent对象中
newEvent =eventInfoMap.get(event.getEventId());
if(null != newEvent ){
aTime = newEvent.getTime();
event.setTime(aTime == null ? "" : sdfMd.format(sdfYmd.parse(aTime )));
event.setIsActionB(newEvent.getIsActionB() == null ? "false" : newEvent.getIsActionB());
event.setUserInfo(newEvent.getUserInfo());
event.setListB(newEvent.getListB());
event.setListC(newEvent.getListC());
}
}
<resultMap id="UserMap" type="User">
<result column="name" property="name" />
<result column="picId" property="picId" />
<result column="time" property="time" />
</resultMap> <resultMap id="BMap" type="EntityB">
<id column="bPhone" property="phone" />
<result column="bUserName" property="userName" />
<result column="bTime" property="time" />
</resultMap> <resultMap id="CMap" type="EntityC">
<id column="cmtId" property="cmtId" />
<result column="referId" property="referId" />
<result column="cUserName" property="userName" />
<result column="referName" property="referName" />
<result column="cTime" property="time" />
</resultMap> <resultMap id="EventResultMap" type="com.xxxx.bean.UserEvent">
<id column="eventId" property="eventId" />
<result column="time" property="time" />
<result column="isActionB" property="isActionB" />
<association property="userInfo" resultMap="UserMap" />
<collection property="listB" resultMap="BMap" />
<collection property="listC" resultMap="CMap" />
</resultMap> <select id="selectUserEventInfo" resultMap="EventResultMap">
SELECT
A.eventId,
A.time,
A.name,
A.picId,
CASE WHEN B.phone = #{phone} THEN "true" ELSE "false" END AS isActionB,
B.phone AS bPhone,
B.userName AS bUserName,
B.time AS bTime,
C.cmtId,
C.referId,
C.userName AS cUserName,
C.referName AS referName,
C.time AS cTime
FROM v_table_a A
LEFT JOIN v_table_b B ON B.eventId = A.eventId
LEFT JOIN v_table_c C ON C.eventId = A.eventId
<where>
A.event_id in
<foreach collection="eventIds" index="" item="eventId"
open="(" separator="," close=")">
#{eventId}
</foreach>
</where>;
</select>
编码时需要注意的几个地方
1. 复杂对象的映射解析
<!-- spring-mybatis.xml文件 -->
<!-- 配置sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 将各Java类的简写别名单独放到文件mybatis.xml中,方便修改和管理 -->
<property name="configLocation" value="classpath:xml/mybatis.xml" />
<property name="mapperLocations" value="classpath:sql/*.xml" />
</bean>
<!-- mybatis.xml文件 -->
<configuration>
<typeAliases>
<typeAlias alias="EntityA" type="com.xxxx.model.EntityA" />
<typeAlias alias="EntityB" type="com.xxxx.model.EntityB" />
<typeAlias alias="EntityC" type="com.xxxx.model.EntityC" />
<typeAlias alias="User" type="com.xxxx.model.User" />
</typeAliases>
</configuration>
2. foreach标签的使用
处理时间对比

【Java】记录一次代码优化的更多相关文章
- JAVA记录-java代码优化策略
java代码优化策略 1.生成对象时,合理分配空间和大小:new ArrayList(100); 2.优化for循环: Vector vect = new Vector(1000); For(int ...
- java记录在线人数小案例
文件目录: web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app version= ...
- JAVA记录-Servlet介绍
1.什么是Servlet Servlet是sun公司提供的一门用于开发动态web资源的技术.Sun公司在其API中提供了一个servlet接口,用户若想用发一个动态web资源(即开发一个Java程序向 ...
- JAVA记录-Mybatis介绍
1.什么是 MyBatis ? MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyB ...
- JAVA记录-JSP内容
JSP(JavaServer Pages )是什么? JavaServer Pages(JSP)是一种支持动态内容开发的网页技术它可以帮助开发人员通过利用特殊的JSP标签,其中大部分以<%开始并 ...
- java 记录对象前后修改的内容(工具类)
有时候业务需要,需记录一条记录的修改历史,但是不能为完成任务而硬编码,不靠谱 这种情况可以使用java反射来完成 对对象属性的描述可以通过自定义注解来完成,读取里面的属性进而记录修改历史. 在对象的属 ...
- java基础一(阅读Head First Java记录)
写在前面的话 在实际应用java中,因为没有系统去看过书或者学习过,所以基础薄弱,刚好这本书是比较入门级的一些书,记录一下下面的一些基本概念,以方便自己来学习.当然如果对大家有帮助也是很好的. 因为书 ...
- java记录linux top命令信息
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.Fi ...
- 初学java记录
记录一: if语句: if(x < y) System.out.println("x is less than y"); 记录二: 强制转换字符类型赋值的方法: num2= ...
随机推荐
- jquery的each
each()方法能使DOM循环结构简洁,不容易出错.each()函数封装了十分强大的循环功能,使用也很方便,它可以循环一维数组.多维数组.DOM, JSON 等等在javaScript开发过程中使用$ ...
- Android内存清理
直接上图吧! 获取文件大小 ,清理文件工具类 public class DataCleanManager { public static String getTotalCacheSize(Contex ...
- Third Day(上班第四天):Android开发环境配置问题相关
换公司新电脑了,重新安装Android开发环境,并配置,具体流程如下:1.百度JDK,访问Oracle官网:http://www.oracle.com/technetwork/java/javase/ ...
- SQL Server 2016中In-Memory OLTP继CTP3之后的新改进
SQL Server 2016中In-Memory OLTP继CTP3之后的新改进 转译自:https://blogs.msdn.microsoft.com/sqlserverstorageengin ...
- AnguarJS 第二天----数据绑定
Terms 今天学习AngularJS双向数据绑定的特性,这里面需要提到两个概念: 数据模型:数据模型是指 $scope对象, $scope对象是简单的javascript对象,视图可以访问其中的属性 ...
- @OutputCache 详解-文章目录
OutputCache概念学习 OutputCache属性详解(一)一Duration.VaryByParam OutputCache属性详解(二)一 Location OutputCache属性详解 ...
- 初学者--bootstrap(四)栅格系统----在路上(8)
---------------------------------------栅格系统:是bootstrap提供的响应式布局方式------------------------------------ ...
- Mysql命令show global status求根溯源
近来,发现好多公司对mysql的性能监控是通过show global status实现的,因此对于这个命令想要探究一番,看他是否是实时更新的. 在此之前,我们必须搞明白mysql对于这个命令的执行过程 ...
- SSISDB5:Parameter
Parameter 是Package 提供给外界的接口,通过传递不同的Parameter value,能够动态控制 Package 执行不同的Task或container,产生不同的结果. 一,Par ...
- LINQ系列:LINQ to XML查询
1. 读取XML文件 XDocument和XElement类都提供了导入XML文件的Load()方法,可以读取XML文件的内容,并转换为XDocument或XElement类的实例. 示例XML文件: ...