1. 程式人生 > >MyBatis二級緩存配置

MyBatis二級緩存配置

oca localhost cto rac char package rop .get ive

正如大多數持久層框架一樣,MyBatis 同樣提供了一級緩存二級緩存的支持

Mybatis二級緩存是SessionFactory,如果兩次查詢基於同一個SessionFactory,那麽就從二級緩存中取數據,而不用到數據庫裏去取了。

  1. 一級緩存: 基於PerpetualCache 的 HashMap本地緩存,其存儲作用域為 Session,當 Session flush 或 close 之後,該Session中的所有 Cache 就將清空

  2. 二級緩存與一級緩存其機制相同,默認也是采用 PerpetualCache,HashMap存儲,不同在於其存儲作用域為 Mapper(Namespace)

,並且可自定義存儲源,如 Ehcache。

啟動二級緩存:

  1.mybatis-config.xml添加

    <setting name="cacheEnabled" value="true"/>

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings
> <setting name="logImpl" value="STDOUT_LOGGING"/> <setting name="cacheEnabled" value="true"/><!-- 二級緩存 --> </settings> <typeAliases> <package name="pojo"/> </typeAliases> <environments default="development"> <
environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/lol?characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="pojo/Product.xml"/> </mappers> </configuration>

  2.在Product.xml(數據庫關系映射)中增加 <cache/>

<?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="pojo">
        <cache/>
        <insert id="addProduct" parameterType="Product" >
            insert into product (name, price) values (#{name}, #{price})    
        </insert>
        <select id="listProduct" resultType="Product">
            select * from  product     
        </select>
         <delete id="deleteProduct" parameterType="Product" >
            delete from product where id= #{id}   
        </delete>
        <select id="getProduct" parameterType="_int" resultType="Product">
            select * from product where id=#{id}
        </select>
        <select id="listProductByIdAndName" resultType="Product">
            <bind name="likename" value="‘%‘ + name + ‘%‘" />
               select * from product 
               <where>
                   <if test="name!=null">
                   and name like #{likename}
                   <if test="price!=null">
                   and price > #{price}
                   </if>
               </if> 
               </where>
               
        </select>
    </mapper>

  3.序列化Product.java(pojo類)

   通常來說,二級緩存的機制裏會有一個: 當緩存的個數達到某個數量的時候,把緩存對象保存在硬盤上。 如果要把對象保存在硬盤上,就必須實現序列化接口。

   序列化相關知識:http://blog.csdn.net/wangloveall/article/details/7992448/

package pojo;

import java.io.Serializable;

public class Product implements Serializable{
 
    private int id;
    private String name;
    private float price;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
}

  4.測試類

package controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import pojo.Product;

public class TestMybatis {
    public static void main(String [] args) throws IOException{
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        
        Product p = session.selectOne("getProduct", 1);
        session.commit();
        session.close();
        
        SqlSession session1 = sqlSessionFactory.openSession();//二級緩存測試
        Product p2 = session1.selectOne("getProduct", 1);
        session1.commit();
        session1.close();
    }
}

  5.結果

技術分享

  

MyBatis二級緩存配置