1.mybatis-config.xml文件中配置开启二级缓存
<settings>
<setting name="logImpl" value="LOG4J"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="cacheEnabled" value="true"/>
</settings>
2.mapper.xml文件中使用cache标签启用二级缓存
<mapper namespace="com.lixv.dao.StudentMapper">
<cache/>
<select id="getStudents" resultType="student" parameterType="map" useCache="true">
select * from mybatis_test.student
<where>
<foreach collection="ids" item="id" index="index" open="(" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
<update id="updateStudent" parameterType="map">
update mybatis_test.student
<set>
<if test="name != null">name = #{name},</if>
<if test="tid != null">tid = #{tid}</if>
</set>
<where>
id = #{id}
</where>
</update>
<select id="getStudentById" parameterType="int" resultType="student">
select * from mybatis_test.student where id = #{id}
</select>
</mapper>
3.使用二级缓存的注意事项
- 只要开启了二级缓存,在同一个Mapper下就有效。
- 所有的数据都会先放到一级缓存中。
- 只有当会话提交或者关闭的时候,才会提交到二级缓冲中!
- 涉及二级缓存的实体类需要继承Serializable接口序列化,否则会报错。