mybatis(25)——开启二级缓存

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.使用二级缓存的注意事项

  1. 只要开启了二级缓存,在同一个Mapper下就有效。
  2. 所有的数据都会先放到一级缓存中。
  3. 只有当会话提交或者关闭的时候,才会提交到二级缓冲中!
  4. 涉及二级缓存的实体类需要继承Serializable接口序列化,否则会报错。

版权声明:本文为qq_45895576原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。