MyBatis 的 XML 配置文件和缓存使用步骤

目录
  • MyBatis缓存介绍
  • MyBatis的XML整体介绍
    • 一、整体配置文件介绍
    • 二、Mybatis拦截器【不做要求】
  • 参考案例
    • 三、缓存
  • 使用步骤

    MyBatis缓存介绍

    正如大多数持久层框架一样,MyBatis 同样提供了一级缓存和二级缓存的支持

    1.一级缓存: 基于PerpetualCache 的 HashMap本地缓存,其存储作用域为 Session,当 Session flush 或 close 之后,该Session中的所有 Cache 就将清空。
    2. 二级缓存与一级缓存其机制相同,默认也是采用 PerpetualCache,HashMap存储,不同在于其存储作用域为 Mapper(Namespace),并且可自定义存储源,如 Ehcache。

    3. 对于缓存数据更新机制,当某一个作用域(一级缓存Session/二级缓存Namespaces)的进行了 C/U/D 操作后,默认该作用域下所有 select 中的缓存将被clear。

    MyBatis 包含一个非常强大的查询缓存特性,它可以非常方便地配置和定制。MyBatis 3 中的缓存实现的很多改进都已经实现了,使得它更加强大而且易于配置。下面给大家详细介绍 MyBatis 的 XML 配置文件和缓存使用步骤,内容如下所示:

    MyBatis的XML整体介绍

    MyBatis 的 XML 配置文件结构如下: 
    configuration 配置 
    	properties 属性
    	settings 设置
    	typeAliases 类型命名
    	typeHandlers 类型处理器
    	objectFactory 对象工厂
    	plugins 插件
    	environments 环境 
    		environment 环境变量 
    		transactionManager 事务管理器
    	dataSource 数据源
    
    	databaseIdProviderchinese?
    	mappers 映射器

    一、整体配置文件介绍

    <properties resource="jdbc.property">
    	<property name="password" value="123456"/>
    </properties>
    
    <?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>
        <!--其他地方可以使用${password}来引用这个变量-->
        <properties resource="jdbc.property">
            <property name="password" value="123456"/>
        </properties>
        <!--MyBatis设置信息-->
        <settings>
            <!--启用延迟加载数据、cacheEnabled,lazyLoadingEnabled-->
            <!--
    			1、延迟加载:用的时候就查询、不用的时候并不会查询
    			2、即使加载:不管你用不用、都会去数据库查询出来
    		-->
            <setting name="cacheEnabled" value="true"/>
            <setting name="lazyLoadingEnabled" value="true"/>
            <!--选择日志、选择后需要导入对应的jar包和配置-->
            <setting name="logImpl" value="log4j"/>
        </settings>
        <!--别名扫描包-->
        <typeAliases>
            <package name="package.mybatis.bean"/>
        </typeAliases>
        <!--数据源设置、可以设置多个数据源environment---
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="${driver}"/>
                    <property name="url" value="${url}"/>
                    <property name="username" value="${username}"/>
                    <property name="password" value="${password}"/>
                </dataSource>
            </environment>
        </environments>
    	<!--Mapper映射文件设置-->
        <mappers>
            <!--XML配置-->
            <mapper resource="package/mybatis/mapper/StudentMapper.xml"/>
            <!--单个接口配置-->
            <mapper class="package.mybatis.dao.StudentDao"/>
            <!--多个接口配置、包扫描模式、一次性配置package.mybatis.dao包下面的所有接口-->
            <package name="package.mybatis.dao"/>
        </mappers>
    </configuration>

    二、Mybatis拦截器【不做要求】

    拦截器名作用
    Executor拦截执行器的方法
    ParameterHandler拦截参数的处理
    ResultHandler拦截结果集的处理
    StatementHandler拦截Sql语法构建的处理

    实际上、Executor就能处理所有、其他的并不怎么好用

    参考案例

    //@Intercepts:标识该类是一个拦截器
    //@Signature:指明自定义拦截器需要拦截哪一个类型,哪一个方法;
    //	type:对应四种类型中的一种;
    //	method:对应接口中的哪类方法(因为可能存在重载方法);
    //	args:方法参数
    @Intercepts({
    	@Signature(type = Executor.class, method = "update", args = { MappedStatement.class,Object.class }),
    	@Signature(type = Executor.class, method = "query", args = { 				MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class })
    })
    public class MyPlugin implements Interceptor {
    	@Override
    	public Object intercept(Invocation invocation) throws Throwable {
    		if ("update".equals(invocation.getMethod().getName())) {
    			MappedStatement mstt = (MappedStatement) invocation.getArgs()[0];
    			Object object = invocation.getArgs()[1];
    			Student info=(Student)object;
                //修改用户sql语句的参数
    			info.setName("我不是汉武帝");
    		}
    		System.out.println("方法执行");
    		return invocation.proceed();
    	}
    	@Override
    	public Object plugin(Object target) {
    		return Plugin.wrap(target, this);
    	}
    	@Override
    	public void setProperties(Properties properties) {
    	}
    }
    <!--配置文件-->
    <plugins>
    	<plugin interceptor="package.plugin.MyPlugin">
    	    <property name="name" value="admin"/>
    	</plugin>
    </plugins>

    三、缓存

    一级缓存 session级别、【默认开启】、增删改默认刷新一级缓存(一定要commit哦)

    一级缓存是SqlSession级别的缓存。在操作数据库时需要构造 sqlSession对象,mybatis 使用HashMap 来存储缓存数据。不同的sqlSession之间的缓存数据区域(HashMap),所以是互不影响的

    二级缓存【默认是关闭、不常用】

    是mapper级别的缓存,多个SqlSession去操作同一个Mapper的sql语句,多个SqlSession可以共用二级缓存,二级缓存是跨SqlSession的

    使用步骤

    1、修改mybatis-config.xml的setting设置
    	<setting name="cacheEnabled" value="true"/>
    2、Mapper.XML:加入:<cache/>
    3、缓存的bean要实现序列化接口 Serializable
    4、一定要关闭第一个sqlSession
    
    //SqlSession:连接对象Connection、mybatis的session并不是会话,指的就是Sql的Connection
    		SqlSession session1 = sqlSessionFactory.openSession();
    		SqlSession session2 = sqlSessionFactory.openSession();
    		
    		//为了使用缓存、sql语句一定要统一规范
    		StudentDao dao1=session1.getMapper(StudentDao.class);
    		System.out.println("查询一次数据");
    		List<Student> list1 = dao1.getStudentAll();
    		for (Student student : list1) {
    			System.out.println(student);
    		}
    		session1.close();
    		System.out.println("第二次查询数据");
    		Thread.sleep(10000);
    		StudentDao dao2=session2.getMapper(StudentDao.class);
    		System.out.println("查询一次数据");
    		List<Student> list2 = dao2.getStudentAll();
    		for (Student student : list2) {
    			System.out.println(student);
    		}

    本文转自网络,如有侵权请联系客服删除。