MYyBatis
性能提升
主要思想:减少查询次数
1. 合并SQL
使用大量的左连接 起别名进行sql合并
为什么?
因为这样可以将多条查询结果合并成一条输出,提高了效率。
selectById是一条结果一条的查询,消耗大量的性能。
注意
左连接 left join xxx on 可以多个添加 连续左连接 没有问题
注意别名问题 避免出现二义性。所以尽量谁的属性就使用别名.属性
select xxx from table1,table2 where t1.xx == t2.xx;
<resultMap id="rm" type="Member" autoMapping="true">
<association property="college" column="college" select="com.ychs.dao.CollegeMapper.selectById">
</association>
<association property="major" column="major" select="com.ychs.dao.MajorMapper.selectById">
</association>
</resultMap>
<resultMap id="rm" type="Competition" autoMapping="true">
<association property="college" column="college" select="com.ychs.dao.CollegeMapper.selectById">
</association>
</resultMap>
<!-- 将SQL合并 -->
<resultMap id="rm" type="Member" autoMapping="true">
<association property="college">
<result column="cid" property="id"></result>
<result column="cname" property="name"></result>
</association>
<association property="major">
<result column="jid" property="id"></result>
<result column="jname" property="name"></result>
</association>
</resultMap>
<!-- 个人建议一般设计resultMap 就打开自动映射 否则只有我们书写的映射对应映射-->
<select id="selectById" resultMap="rm">
select m.id,m.college,m.major,m.code,sex,grade,native_place,
phone,school_job,join_date,state,lab_job,remark,m.name,
c.id cid,c.name cname,j.id jid,j.name jname
from member m LEFT JOIN college c on m.college = c.id
LEFT JOIN major j ON m.major = j.id
WHERE m.id=#{id}
</select>
2. 缓存
目的:提升查询效率和减少数据库的压力
分为一级缓存和二级缓存
一级缓存是默认打开的,二级缓存需要配置。
一级缓存是一个会话 session中 范围较小
缓存失效:
1.当主动调用session的clearCache方法时 会清空缓存
2.当会话中发生了更新操作后,缓存失效
注意:
如果不清空缓存,调用同一个查询,会自动在内存中查找,不需要链接数据库。但是如果清空缓存,则需要重新链接数据库,消耗内存,拖慢运行速度。
二级缓存是一个命名空间 多个seesion共同的空间,xml中配置的命名空间
二级缓存还是依赖一级缓存,当一起混村手动情况或发生更新操作而导致的清空,二级缓存会失效。
MyBatis 的开关
<setting name="cacheEnabled" valued="true">
在小的mapper中打开小开关
<cache/>
3. 延迟加载
<setting>
<!-- 启用延迟加载特性 不配置 -->
<setting name="lazyLoadingEnabled" value="true">
</setting>
<!-- 积极加载开关-->
<setting name="aggressiveLazyLoading" value="false">
</setting>
<!--触发加载开关 -->
<setting name="lazyLoadTriggerMethods" vaule="">
</setting>
分页查询
排序字段是不固定的,排序方式不固定,需要传入MyBatis中
order by ‘xx’ ‘asc/desc’ 错的 #{xxx}会加单引号
order by ${orderColumn} ${order Type}
limit #{begin},#{pageSize}
先排序 在分页
MyBatis一次查询多条记录
- 首先在数据库连接URL上加上allowMultiQueries=true,默认mysql是不支持一次执行多条SQL语句的。
jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true