表结构如下:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(16) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表';
CREATE TABLE `user_info` (
`userId` int(11) NOT NULL,
`idNumber` varchar(18) DEFAULT NULL COMMENT '身份证号',
`realName` varchar(40) DEFAULT NULL,
`birthday` date DEFAULT NULL,
`sex` char(1) DEFAULT NULL COMMENT '男:1 女:0',
PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
UserMapper如下:
<mapper namespace="com.xxx.mapper.UserMapper">
<span style="color:#ff0000;"><strong><cache/></strong></span>
<resultMap id="User" type="com.xxx.entity.User">
<id property="userId" column="id"/>
<result property="username" column="username"/>
<!-- 表关联 1:1 -->
<association property="userInfo" column="id"
select="com.xxx.mapper.UserInfoMapper.findUserInfoByUserId"/>
</resultMap><pre name="code" class="html"><span style="white-space:pre"> </span><!-- 根据userId查找用户 -->
<select id="findByUserId" resultMap="User">
SELECT u.id,
u.username,
info.realName,
info.idNumber,
info.birthday,
info.sex
FROM user u LEFT JOIN user_info info ON u.id = info.userid WHERE u.id = #{userId} AND isDeleted = '0'
</select>
UserInfoMapper如下:
<mapper namespace="com.xxx.mapper.UserInfoMapper">
<span style="color:#ff0000;"><strong><cache/></strong></span>
<resultMap id="UserInfo" type="com.xxx.entity.UserInfo">
<id property="userId" column="userId"/>
<result property="idNumber" column="idNumber"/>
<result property="realName" column="realName"/>
<result property="birthday" column="birthday"/>
<result property="sex" column="sex"/>
</resultMap>
我是把user和userinfo 1:1关联到一块,在进行数据查找时,如service.findUserByUserId(1);操作,Mybatis会将数据加到缓存中,后续的findUserByUserId不会对数据库查找。但是,如果我此时更新UserInfo呢?
结果很残酷,findUserByUserId查询的依然是缓存,如何才能将被关联的表的cache清空,查询数据库呢?
此时需要使用标签<cache/> <cache ref/>。
<mapper namespace="com.xxx.mapper.UserMapper">
<span style="color:#ff0000;"><strong><cache-ref namespace="com.xxx.mapper.UserInfoMapper"/></strong></span>
<resultMap id="User" type="com.xxx.entity.User">
<id property="userId" column="id"/>
<result property="username" column="username"/>
<!-- 表关联 1:1 -->
<association property="userInfo" column="id"
select="com.xxx.mapper.UserInfoMapper.findUserInfoByUserId"/>
</resultMap><pre name="code" class="html"><span> </span><!-- 根据userId查找用户 -->
<select id="findByUserId" resultMap="User">
SELECT u.id,
u.username,
info.realName,
info.idNumber,
info.birthday,
info.sex
FROM user u LEFT JOIN user_info info ON u.id = info.userid WHERE u.id = #{userId} AND isDeleted = '0'
</select>
UserInfoMapper如下:
<mapper namespace="com.xxx.mapper.UserInfoMapper">
<span style="color:#ff0000;"><strong><cache/></strong></span>
<resultMap id="UserInfo" type="com.xxx.entity.UserInfo">
<id property="userId" column="userId"/>
<result property="idNumber" column="idNumber"/>
<result property="realName" column="realName"/>
<result property="birthday" column="birthday"/>
<result property="sex" column="sex"/>
</resultMap>