Mybatis
在没有特殊的要求下使用resultType,如果要关联查询的结果映射到相应的pojo中去则使用resultType
- 一对一的查询
// A code block
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="www.com.inone.userdao.OrdersMapperCustomer">
<!--id唯一标识 type 映射的pojo-->
<resultMap id="OrdersUserCustomer" type="www.com.inone.pojo.Orders">
<id column="id" property="id"></id>
<result column="user_id" property="userId"></result>
<result column="number" property="number"></result>
<result column="createtime" property="createtime"></result>
<result column="note" property="note"></result>
<!--配置映射的用户关联信息-->
<!--association用于关联查询单个对象的信息-->
<association property="user" javaType="www.com.inone.pojo.User">
<id column="user_id" property="id"></id>
<result column="username" property="userName"></result>
<result column="sex" property="sex"></result>
<result column="address" property="address"></result>
</association>
</resultMap>
<select id="findOrdersUser" resultType="www.com.inone.pojo.UserCustom">
SELECT orders.*,user.username,user.sex,user.address FROM orders,USER WHERE orders.user_id=user.id
</select>
<select id="findOrdersUsers" resultMap="OrdersUserCustomer">
SELECT orders.*,user.username,user.sex,user.address FROM orders,USER WHERE orders.user_id=user.id
</select>
</mapper>
- 一对多的映射
mybatis的缓存
一级缓存是sqlSession级别的缓存,二级缓存是存在与Mapper(namespace)中的。
在进行commit操作之后会清空一级和二级缓存。
* 二级缓存
mybatis 的二级缓存的作用域是一个mapper的namespace ,同一个namespace中查询sql可以从缓存中命中。
var foo = 'bar';
//1、在总配置文件中添加
<setting name="cacheEnabled" value="true"/>
//2、在子配置文件中
<mapper namespace="com.zpc.mybatis.dao.UserMapper">
<cache/>
</mapper>
//3、设置pojo开启序列化
为了将缓存数据取出进行反序列化
useCach=“false” (禁用缓存) ---针对每次都需要最新的 sql
<select id="findOrdersUser" resultType="www.com.inone.pojo.UserCustom" useCache="false">
默认是true
flushCache=“false” (清除缓存) ---一般执行完commit操作之后都需要进行刷新缓存,flushCache=true表示刷新缓存,避免数据的脏读。一般都设置成true
<select id="findOrdersUser" resultType="www.com.inone.pojo.UserCustom" flushCache="true">
分布式缓存
- mybatis无法实现分布式缓存,所以mybatis要和其他的分布式缓存框架进行整合
Mybatis和ehcache整合(实现cach接口)
1、<cache type="org.mybatis.caches.ehcache.EncacheCache’/>
2、在classpath下配置ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="F:\develop\ehcache" />
<defaultCache
maxElementsInMemory="1000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
- 二级缓存的应用场景:对于访问多的查询请求且用户对查询的结果实时性要求不高的。
- 实现方法:通过设置刷新间隔时间,有mybatis每隔一段时间自动清空缓存,根据数据变化的频率设置刷新间隔flushInterval,例如设置:30,60分钟等。
- 二级缓存的局限性:mybatis的二级缓存对细粒度的数据实现不好。解决办法:自己手动实现业务层缓存(三级缓存)。
Spring整合Mybatis
SpringBoot整合Mybatis
Mybatis逆向工程
-
方式:1、Mybatis-plus (功能过于强大)2、TK-Mybatis(目前使用最多)
-
使用步骤:
-
Mybatis整合springboot 框架源码:https://github.com/abel533/MyBatis-Spring-Boot 在github上面可以下载源码