Mybatis入门详解

1、第一个mybatis程序

1.1、编写mybatis核心配置文件mybatis-config.xml(记得每个mapper.xml都需要进行注册)

<?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">
<!--mybatis核心配置文件-->
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/><!--事务管理器,有两种-->
            <dataSource type="POOLED"><!--数据源-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--每个mapper.xml都需要在mybatis核心配置文件中注册-->
    <mappers>
        <mapper resource="com/kuang/Dao/UserMapper.xml"/>
    </mappers>
</configuration>

mappers这个配置中,如果使用注解则用class,使用mapper.xml则使用resource

<!--每一个mapper.xml都要在mybatis的核心配置文件中注册-->
    <!--注解-->
    <mappers>
    <mapper class="com.kuang.dao.userMapper" />
        </mappers>
<!--mapper.xml-->
    <mappers>
    <mapper resource="com/kuang/Dao/UserMapper.xml"/>
    </mappers>

1.2、编写mybatis工具类mybatisUitls(用来生产sqlsession)

package com.kuang.util;

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 java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {
    public static SqlSessionFactory sqlSessionFactory ;
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

1.3、maven配置资源导出解决问题

<!--maven资源导出问题解决方案-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

1.4、编写userMapper(即userdao接口)

public interface UserMapper {

    List<User> getUserList();
}

1.5、编写userMapper.xml

<?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">
<!--一个namespace对应一个userMapper-->
<!--namespace命名空间 :对应的userdao全路径;id:对应的方法名;resultType:返回类型的全路径-->
<mapper namespace="com.kuang.Dao.UserMapper">
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from mybatis.user;
    </select>
</mapper>

2、CRUD

注意

所有的增删改都需要提交事务,JDBC默认提交事务,mybatis手动提交事务

parameterType:参数类型的类路径
resultType:返回结果的类路径
id:namespace对应的userMapper的方法名

2.1、查询

	<!--查询所有用户-->
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from mybatis.user;
    </select>
    
    <!--根据用户id查询用户-->
    <select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User">
        select * from mybatis.user where  id= #{id};
    </select>

2.2、增加

	<!--增加用户-->
    <insert id="insertUser" parameterType="com.kuang.pojo.User">
        insert `user` (`id`,`name`,`pwd`) value (#{id},#{name},#{pwd});
    </insert>

2.3、修改

	 <!--修改用户-->
    <update id="updateUser" parameterType="com.kuang.pojo.User" >
        update `user` set `name` =#{name},`pwd`=#{pwd}  where `id` = #{id} ;
    </update>

2.4、删除

	<!--删除用户-->
    <delete id="deleteUser" parameterType="int">
        delete from `user` where `id` = #{id};
    </delete>

2.5、模糊查询

 <!--模糊查询-->
    <select id="getUserByLike" parameterType="String" resultType="com.kuang.pojo.User">
        select * from mybatis.user where name like #{value};
    </select>

3、万能的map

Map传递参数,直接在SQL中取出key即可

对象传递参数,直接在SQL中取对象的属性即可

只有一个基本类型参数的情况下,可以直接在sql中取到

多个参数用map,或者注解!

 //万能的map:适用于多个参数时
    int updateU(Map<String,Object> map);
<!--万能的map-->
<update id="updateU" parameterType="map" >
    update `user` set `name` = #{userName},`pwd` = #{password} where `id` = #{userId};
</update>
@Test
public void Test6(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("userName","郑小七");
    map.put("userId","1");
    map.put("password","123456");
    int result = mapper.updateU(map);
    if(result > 0){
        System.out.println("修改成功");
        sqlSession.commit();
    }
    System.out.println();
    sqlSession.close();
}

4、配置解析

configuration(配置)

4.1、环境配置(environments)

可以配置多个环境,只能选择一种环境

<environments default="development">
  <environment id="development">
    <transactionManager type="JDBC">
      <property name="..." value="..."/>
    </transactionManager>
    <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>

事务管理器(transactionManager)

在MyBatis中有两种类型的事务管理器

  • JDBC – 这个配置直接使用了 JDBC 的提交和回滚设施,它依赖从数据源获得的连接来管理事务作用域。

  • MANAGED – 这个配置几乎没做什么。

注意

如果你正在使用 Spring + MyBatis,则没有必要配置事务管理器,因为 Spring 模块会使用自带的管理器来覆盖前面的配置

4.2、属性(properties)

#db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
username=root
password=123456
 	<!--引入外部配置文件-->
	<properties resource="db.properties">
        
    </properties>
   

4.3、类型别名(typeAliases)

 <!--可以给实体类起别名-->
    <typeAliases>
        <!--方式一-->
        <typeAlias type="com.kuang.pojo.User" alias="user"/>
        <!--方式二
        在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名
        -->
        <package name="com.kuang.pojo"/>
    </typeAliases>

4.4、设置(settings)

这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Q2I9oLyv-1608309043628)(C:\Users\ASUS\Desktop\Jersey-笔记\捕获3.PNG)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-X1X1KnMr-1608309043637)(C:\Users\ASUS\Desktop\Jersey-笔记\捕获4.PNG)]

4.5、映射器(Mappers)

  • 接口名和他的配置文件名保持同名
  • 接口和他的配置文件在同一级包下

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jbufjApI-1608309043642)(C:\Users\ASUS\Desktop\Jersey-笔记\捕获1021.PNG)]

4.6、生命周期和作用域

同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题

SqlSessionFactoryBuilder

  • 一旦创建了 SqlSessionFactory,就不再需要它了
  • SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)
  • 不要一直保留着它,以保证所有的 XML 解析资源可以被释放给更重要的事情
SqlSessionFactory
  • 一旦被创建就应该在应用的运行期间一直存在
  • SqlSessionFactory 的最佳作用域是应用作用域
  • 最简单的就是使用单例模式或者静态单例模式
SqlSession
  • SqlSession 的实例不是线程安全的,因此是不能被共享的
  • 为了确保每次都能执行关闭操作,你应该把这个关闭操作放到 finally 块中

4.7、解决数据库中字段名和实体类中属性名不一致的问题

在mapper.xml文件中设置resultMap

<!--结果集映射-->
<resultMap id="UserMap" type="User">
    <!--column:数据库中字段名,property:实体类中的属性名-->
    <result column="pwd" property="password"/>
</resultMap>

<!--查询所有的用户-->
<select id="getUserList" resultMap="UserMap">
    select * from mybatis.user;
</select>

5、日志

5.1、日志工厂和STDOUT_LOGGING

如果一个数据库操作,出现了错误,需要排错,那日志就是最好的助手

<settings>
    <!--标准的日志工厂配置-->
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-T2eKHfCN-1608309043648)(C:\Users\ASUS\Desktop\Jersey-笔记\日志1.PNG)]

  • SLF4J
  • LOG4J 【掌握】
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING 【掌握】
  • NO_LOGGING

有日志时运行显示的

Opening JDBC Connection
Created connection 1574598287.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@5dda768f]
==>  Preparing: select * from mybatis.user where id= ?; 
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 郑小七, 123456
<==      Total: 1
User{id=1, name='郑小七', password='123456'}
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@5dda768f]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@5dda768f]
Returned connection 1574598287 to pool.

5.2、log4j

1、导入log4j的包或maven依赖

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

2、log4j.properties

#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file

#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold = DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern = [%c]-%m%n

#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File = ./log/kuang.log
log4j.appender.file.MaxFileSize = 10mb
log4j.appender.file.Threshold = DEBUG
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = [%p][%d{yy-MM-dd}][%c]%m%n

#日志输出级别
log4j.logger.org.mybatis = DEBUG
log4j.logger.java.sql = DEBUG
log4j.logger.java.sql.statment = DEBUG
log4j.logger.java.sql.ResultSet = DEBUG
log4j.logger.java.sql.PreparedStatement = DEBUG

3、配置log4j为日志的实现

<settings>
    <!--标准的日志工厂配置-->
    <!-- <setting name="logImpl" value="STDOUT_LOGGING"/>-->
    <setting name="logImpl" value="log4j"/>
</settings>

简单使用

(1)、在要使用log4j的类中,导入包

org.apache.ibatis.logging.log4j.Log4jImpl;

(2)、日志对象,当前类的class

public class UserTest {

    static Logger logger = Logger.getLogger(UserTest.class);

(3)、日志级别

logger.info("info:进入了testLog4j");
logger.debug("debug:进入了testLog4j");
logger.error("error:进入了testLog4j");

6、分页

6.1、使用limit分页

--语法
select * from user limit startIndex,pageSize

1、接口

//分页
List<User> getUserByLimit(Map<String,Integer> map);

2、Mapper.xml

<!--分页-->
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
    select * from mybatis.user limit #{startIndex},#{pageSize};
</select>

3、测试

//分页
@Test
public void testLimit(){
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    Map<String,Integer> resultMap = new HashMap<String,Integer>();
    resultMap.put("startIndex",0);
    resultMap.put("pageSize",2);
    List<User> userList = mapper.getUserByLimit(resultMap);
    for (User user : userList) {
        System.out.println(user);
    }
    sqlSession.close();
}

6.2、Rowbounds实现分页

1、接口

//分页2
List<User> getUserByRowBounds();

2、mapper.xml

<!--分页2-->
<select id="getUserByRowBounds" resultMap="UserMap">
    select * from mybatis.user ;
</select>

3、测试

//使用rowBounds实现分页
@Test
public void testRowBounds(){
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    RowBounds rowBounds = new RowBounds(0,2);
    List<User> userList = sqlSession.selectList("com.kuang.Dao.UserMapper.getUserByRowBounds", null, rowBounds);
    for (User user : userList) {
        System.out.println(user);
    }
    sqlSession.close();
}

7、使用注解开发

只适用于简单sql

7.1、crud

方法存在多个参数,所有参数前面必须加上@param注解

//方法存在多个参数,所有参数前面必须加上@param注解
@Select("select * from user")
List<User> getUsers();

@Insert("insert into user (`id`,`name`,`pwd`) value(#{id},#{name},#{pwd})")
int insertUser(User user);

@Update("update user set`name` = #{uName},`pwd` = #{uPwd} where `id` = #{uid}")
int updateUser(@Param("uid") int id,@Param("uName") String name,@Param("uPwd") String password);

@Delete("delete from user where `id` = #{uid}")
int deleteUser(@Param("uid") int id);

7.2、自动提交

在工具类创建时可设置自动提交

public static SqlSession getSqlSession(){
    return sqlSessionFactory.openSession(true);
}

8、关于@param和#{},${}

8.1、@param

(1)、@select、@insert、@update、@delete这些注解告诉mybatis执行括号里的sql

但由于没有xml文件,要正确的传入参数,那么就要给参数命名,在方法参数的前面写上**@Param(“参数名”),表示给参数命名,名称就是括号中的内容**

public interface Mapper { 
    @Select("select s_id ,s_name ,class_id  from student where  s_name= #{aaaa} and class_id = #{bbbb}") 
    public Student select(@Param("aaaa") String name,@Param("bbbb")int class_id);  

    @Delete...... 

        @Insert...... 

}  

9、多对一处理

public interface StudentMapper {
    /*查询所有学生信息,以及对应的老师信息*/
    List<Student> getStudentList();

    List<Student> getStudentList2();
}

9.1、按照查询嵌套处理

<!--
    思路
    1、查询所有的学生信息
    2、根据查询出来的tid,找对应的teacher信息
    -->
    <select id="getStudentList" resultMap="student-teacher">
        select * from mybatis.student
    </select>

    <!--复杂的属性,我们需要单独处理,association :对象;collection:集合-->
    <resultMap id="student-teacher" type="student">
        <association property="teacher" column="tid" javaType="teacher" 		          select="getTeacher"/>
    </resultMap>

    <select id="getTeacher" resultType="teacher">
        select * from mybatis.teacher where id = #{id}
    </select>

9.2、按照结果嵌套处理

<!--
    按结果嵌套处理
    -->
<select id="getStudentList2" resultMap="student-teacher2">
   	select s.id sid,s.name sname,t.name tname
   	from mybatis.student s,mybatis.teacher t where s.tid = t.id;
</select>
<resultMap id="student-teacher2" type="student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="teacher">
    <result property="name" column="tname"/>
    </association>
</resultMap>

9.3、回归MySQL的多对一查询方式

  • 子查询
  • 联表查询

10、一对多处理

按结果嵌套查询

实体类

public class teacher {
    private int id;
    private String name;
    private List<student> studentList;
}

mapper.xml

<!--按结构嵌套查询-->
<select id="getTeacherById" parameterType="int" resultMap="teacher-student">
    select  t.name tname,t.id tid, s.name sname,s.id sid
    from mybatis.teacher t,mybatis.student s
    where t.id = #{id};
</select>

<resultMap id="teacher-student" type="teacher">
    
    <id property="id" column="tid"/>
    <result property="name" column="tname"/>
    
    <!--property:实体类属性;oftype:集合里面的·类型;column:字段名-->
    <collection property="studentList" ofType="student">
        <result property="name" column="sname"/>
        <result property="id" column="sid"/>
    </collection>
</resultMap>

11、动态SQL

什么是动态SQL:动态sql就是指根据不同的条件生成不同的sql语句

  • if
  • choose(when,otherwise)
  • trim(where ,set)
  • foreach

11.1、if标签

mapper接口

List<Blog> getBlogIf(Map map);

mapper.xml

<select id="getBlogIf" resultType="blog">
    select * from mybatis.blog where 1=1
    <if test="title != null">
        and `title` = #{title}
    </if>
    <if test="author != null">
        and `author` = #{author}
    </if>
</select>

测试

@Test
public void test2(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap<String, String> map = new HashMap<String, String>();
    List<Blog> blogIf = mapper.getBlogIf(map);
    for (Blog blog : blogIf) {
        System.out.println(blog);
    }
    sqlSession.close();
}

11.2、choose标签

mapper接口

List<Blog> getBlogIf2(Map map);

mapper.xml

<select id="getBlogIf2" resultType="blog">
    select * from mybatis.blog
    <where>
        <choose>
            <when test="title != null">
                and title = #{title}
            </when>
            <when test="author != null">
                and author = #{author}
            </when>
            <otherwise>
                and id = #{id}
            </otherwise>
        </choose>
    </where>
</select>

测试

@Test
public void test3(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("title","java如此简单");
    map.put("author","狂神说");
    map.put("id","862aa54768db4e3ca5fae0b390ca05c6");
    List<Blog> blogIf2 = mapper.getBlogIf2(map);
    for (Blog blog : blogIf2) {
        System.out.println(blog);
    }
    sqlSession.close();
}

11.3、trim(where、set)

mapper接口

int updateBlog(Map map);

mapper.xml

<update id="updateBlog" parameterType="map">
    update mybatis.blog
    <set>
        <if test="title != null">
            title = #{title},
        </if>
        <if test="author != null">
            author = #{author},
        </if>
    </set>
    where id = #{id};
</update>

测试

@Test
public void test4(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("id","862aa54768db4e3ca5fae0b390ca05c6");
    map.put("title","javaWeb如此简单");
    map.put("author","彬仔");
    int result = mapper.updateBlog(map);
    /*
                * 增删改记得提交事务,
                * jdbc自动提交事务
                * mybatis手动提交事务
                * */
    sqlSession.commit();
    if(result > 0 ){
        System.out.println("修改成功");
    }
    sqlSession.close();
}

11.4、foreach标签

mapper接口

List<Blog> queryBlogForeach(Map map);

mapper.xml

<!--传递一个万能的map,map中可能包含list集合-->
<select id="queryBlogForeach" resultType="blog">
    select * from  mybatis.blog
    <where>
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id = #{id}
        </foreach>
    </where>
</select>

测试

@Test
public void test5(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap map = new HashMap();
    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    map.put("ids",list);
    List<Blog> blogs = mapper.queryBlogForeach(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlSession.close();
}

11.5、sql片段

有时候会将一些功能片段提取出来,方便复用

(1)、使用sql标签提取公共部分

<!--sql片段-->
<sql id="if_else" >
    <if test="title != null">
        title = #{title},
    </if>
    <if test="author != null">
        author = #{author},
    </if>
</sql>

(2)、在需要引用的地方用include调用

<update id="updateBlog" parameterType="map">
    update mybatis.blog
    <set>
        <include refid="if_else" />
    </set>
    where id = #{id};
</update>

12、缓存

12.1、mybatis缓存简介

1、默认情况下只有一级缓存(SQLSession级缓存,也称为本地缓存)开启
2、二级缓存需要手动配置和开启,它是基于namespace级别的缓存,mapper.xml
3、对于缓存更新机制,当某个作用域(一级缓存Session/二级缓存Namespaces)进行了CUD操作后,所有的select的缓存都会被清除(清除还是刷新暂定)   

12.2、一级缓存

测试

@Test
public void test(){
    SqlSession sqlSession = mybatisUtils.getSqlSession();
    /*
     * 一级缓存默认开启,只在一次SQLSession中有效,增删改会刷新缓存,也可手动刷新
     * */
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    User user = mapper.queryUser(1);
    System.out.println(user);

    System.out.println("= = = = = = = = = = = = = = ");
    User user1 = mapper.queryUser(1);
    System.out.println(user1);
    sqlSession.close();
}

运行结果

Opening JDBC Connection
Created connection 471579726.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1c1bbc4e]
==>  Preparing: select * from mybatis.user where id = ? 
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 郑小七, 123456
<==      Total: 1
User{id=1, name='郑小七', pwd='123456'}
= = = = = = = = = = = = = = 
User{id=1, name='郑小七', pwd='123456'}
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1c1bbc4e]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1c1bbc4e]
Returned connection 471579726 to pool.

12.3、二级缓存

提示

二级缓存是事务性的,当SQLSession完成并提交或完成并回滚,但没有执行 flushCache=true 的 insert/delete/update 语句时,缓存会获得更新

要启动二级缓存,需要在mybatis核心配置文件和sql映射文件中添加一行

<!--重要设置-->
<settings>
    <!--开启二级缓存-->
    <setting name="cacheEnabled" value="true"/>
</settings>
<!--
        eviction:清除策略
            LRU  最近最少使用:移除最长时间不被使用的对象
            FIFO  先进先出:按对象进入缓存的顺序来移除
            SOFT
            WEAK
            默认清除策略是LRU
        flushInterval:刷新间隔,以毫秒为单位
        size:引用数目
            默认值为1024
        readOnly:只读
            设置为true时会给调用者返回缓存对象相同的实例
            设置为false时缓存会(通过序列化)返回缓存对象的拷贝,可以读写,速度相对会慢一点,但更安全
-->
<cache eviction="LRU"
       flushInterval="6000"
       size="1024"
       readOnly="false"/>

测试类

@Test
public void test1(){
    SqlSession sqlSession1 = mybatisUtils.getSqlSession();
    SqlSession sqlSession2 = mybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession1.getMapper(UserMapper.class);
    User user = mapper.queryUser(1);
    System.out.println(user);
    System.out.println("= = = = = = = = = = = = = = = = = ");
    UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
    User user1 = mapper1.queryUser(1);
    System.out.println(user1);
    sqlSession1.close();
    sqlSession2.close();
}

测试结果

Opening JDBC Connection
Created connection 593687897.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@2362f559]
==>  Preparing: select * from mybatis.user where id = ? 
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 郑小七, 123456
<==      Total: 1
User{id=1, name='郑小七', pwd='123456'}
= = = = = = = = = = = = = = = = = 
Cache Hit Ratio [com.kuang.dao.UserMapper]: 0.0
User{id=1, name='郑小七', pwd='123456'}
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@2362f559]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@2362f559]
Returned connection 593687897 to pool.

/>


测试类

```java
@Test
public void test1(){
    SqlSession sqlSession1 = mybatisUtils.getSqlSession();
    SqlSession sqlSession2 = mybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession1.getMapper(UserMapper.class);
    User user = mapper.queryUser(1);
    System.out.println(user);
    System.out.println("= = = = = = = = = = = = = = = = = ");
    UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
    User user1 = mapper1.queryUser(1);
    System.out.println(user1);
    sqlSession1.close();
    sqlSession2.close();
}

测试结果

Opening JDBC Connection
Created connection 593687897.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@2362f559]
==>  Preparing: select * from mybatis.user where id = ? 
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 郑小七, 123456
<==      Total: 1
User{id=1, name='郑小七', pwd='123456'}
= = = = = = = = = = = = = = = = = 
Cache Hit Ratio [com.kuang.dao.UserMapper]: 0.0
User{id=1, name='郑小七', pwd='123456'}
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@2362f559]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@2362f559]
Returned connection 593687897 to pool.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值