欢迎投稿

今日深度:

Mybatis小白入门,它支持自定义SQL、

Mybatis小白入门,它支持自定义SQL、


Mybatis-9.28

环境:

  • JDK:1.8
  • Mysql:8.032
  • maven:3.9.2
  • IDEA

回顾:

  • JDBC
  • Mysql
  • JavaSE
  • Maven
  • Junit

01 简介

1.1 什么是MyBatis

  • MyBatis 是一款优秀的持久层框架。
  • 它支持自定义 SQL、存储过程以及高级映射。
  • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
  • MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

如何获得Mybatis?

  • maven仓库:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.13</version>
</dependency>
  • Github:https://github.com/mybatis/mybatis-3/releases
  • 中文文档:https://mybatis.org/mybatis-3/zh/index.html

1.2 持久化

数据持久化

  • 持久化就是将程序的数据在持久状态和瞬时状态转化的过程

  • 内存:断电即失

  • 数据库(jdbc),io文件持久化。

为什么需要持久化?

  • 有一些对象,不能让他丢掉。

  • 内存太贵了

1.3 持久层

Dao层 Service层 Controller层。。。

  • 帮助程序员将数据存入数据库中
  • 方便
  • 传统的JDBC太复杂了。简化、框架、自动化。
  • 不用Mybatis也可以。但更容易上手。
  • 优点:
    • 简单易学
    • 灵活
    • sql和代码的分离,提高了可维护性。
    • 提供映射标签,支持对象与数据库的ORM字段关系映射。
    • 提供对象关系映射标签,支持对象关系组建维护。
    • 提供xml标签,支持编写动态sql。

02 第一个Mybatis程序

思路:搭建环境-->导入Mybatis-->编写代码-->测试

2.1 搭建环境

  • 搭建数据库

  • 新建项目

    • 新建一个普通maven项目
    • 删除src目录,使该项目成为父工程
    • 导入maven依赖
     <dependencies>
            <!--数据库连接-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.31</version>
            </dependency>
            <!--mybatis-->
            <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.13</version>
            </dependency>
            <!--junit测试包-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.2</version>
            </dependency>
        </dependencies>
    

2.2 创建一个模版

  • 编写mybatis核心配置文件

    • 记住修改driver、url、username和password
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
      PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
      "https://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
      <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>
      <mappers>
        <mapper resource="你自己配置的xml文件路径"/>
      </mappers>
    </configuration>
    
  • 编写mybatis工具类

        /*提升对象作用域*/
        private static SqlSessionFactory sqlSessionFactory;
    
        static{
            try {
                //使用mybatis第一步,获取sqlSessionFactory对象
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
    
        //既然有了SqlSessionFactory,顾名思义,我们就可以从中获得SqlSession的实例了。
        //SqlSession完全包含了面向数据库执行SQL命令所需的全部方法。
    
        public static SqlSession getsqlSession(){
            return sqlSessionFactory.openSession();
        }
    
    

2.3 编写代码

  • 实体类(注意和数据库表保持一致)

     private int id;
    
        private String name;
    
        private String pwd;
    
        private Date createTime;
    
        private Date modifyTime;
    
        public User() {
    
        }
    
        public User(int id, String name, String pwd, Date createTime, Date modifyTime) {
            this.id = id;
            this.name = name;
            this.pwd = pwd;
            this.createTime = createTime;
            this.modifyTime = modifyTime;
        }
    
        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 String getPwd() {
            return pwd;
        }
    
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
    
        public Date getCreateTime() {
            return createTime;
        }
    
        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }
    
        public Date getModifyTime() {
            return modifyTime;
        }
    
        public void setModifyTime(Date modifyTime) {
            this.modifyTime = modifyTime;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", pwd='" + pwd + '\'' +
                    ", createTime=" + createTime +
                    ", modifyTime=" + modifyTime +
                    '}';
        }
    
  • Dao接口

     List<User> getUserList();
    
  • Dao接口实现类由原来的UserDaoImpl转变为一个Mapper配置文件

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <!--绑定一个对应的Dao/Mappper接口-->
    <mapper namespace="com.wu.dao.UserDao">
        <!--select查询语句-->
        <select id="getUserList" resultType="com.wu.pojo.User">
            select * from mybatis.user
        </select>
    </mapper>
    

2.4 测试

注意点!!!!

首先需要注意一个需要修改的地方,即2.2创建模版中有一处需要配置自己xml地址的地方,在正式运行前需要更改文件路径。路径格式为:

<mapper resource="org/mybatis/example/BlogMapper.xml"/>

在test中编写测试类方法:

    public void test(){

        //第一步:获得SqlSession对象
        SqlSession sqlSession = MybatisUtils.getsqlSession();
        //执行SQL
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();

        for (User user:userList){
            System.out.println(user);
        }
        //关闭SqlSession
        sqlSession.close();

    }

常见易错问题:

1、配置文件没有注册

2、绑定接口有问题

3、方法名不对

4、返回类型不对

5、Maven导出资源问题

补充:作用域和生命周期

  • SqlSessionFactoryBuilder

    • 这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。 因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)。 你可以重用 SqlSessionFactoryBuilder 来创建多个 SqlSessionFactory 实例,但最好还是不要一直保留着它,以保证所有的 XML 解析资源可以被释放给更重要的事情。
  • SqlSessionFactory

    • SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。 使用 SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次,多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。因此 SqlSessionFactory 的最佳作用域是应用作用域。 有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式。
  • SqlSession

    • 每个线程都应该有它自己的SqlSession实例。SqlSession的的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。 绝对不能将 SqlSession 实例的引用放在一个类的静态域,甚至一个类的实例变量也不行。 也绝不能将 SqlSession 实例的引用放在任何类型的托管作用域中,比如 Servlet 框架中的 HttpSession。 如果你现在正在使用一种 Web 框架,考虑将 SqlSession 放在一个和 HTTP 请求相似的作用域中。 换句话说,每次收到 HTTP 请求,就可以打开一个SqlSession,返回一个响应后,就关闭它。 这个关闭操作很重要,为了确保每次都能执行关闭操作,你应该把这个关闭操作放到 finally 块中。

03 CRUD

3.1 Select

  • 选择,查询语句
    • id:就是对应的namespace中的方法名;
    • resultType:Sql语句执行的返回值
    • parameterType:传入的参数类型

注意:增删改需要提交事务!!

3.2-3.4 Insert Update Delete(暂缺,后续补齐)

3.5 分析错误

  • 标签注意不要配错
  • resource绑定mapper,需要使用路径(需要注意resource地址采取“/”和mapper中关于parameterType的配置采取“.”)
  • 程序的配置文件必须符合规范
  • NullPointerException,没有注册到资源!
  • 输出的xml文件中存在中文乱码问题!
  • maven资源节点导出问题!

3.6 Map和模糊查询

3.6.1 Map

假设,实体类或者数据库中的表,字段或者参数过多,应当考虑使用Map!(主要在修改update类型中使用)

int addUserByMap(Map<String, Object> map);
 <insert id="addUserByMap" parameterType="map">
        insert into mybatis.user values(#{id},#{name},#{pwd},#{createTime},#{modifyTime});
 </insert>
@Test
    public void test6(){
        SqlSession sqlSession = MybatisUtils.getsqlSession();

        UserMapper map = sqlSession.getMapper(UserMapper.class);
        Map<String, Object> user = new HashMap<String,Object>();
        user.put("id",4);
        user.put("name","liutianbo");
        user.put("pwd","666666");
        user.put("createTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date().getTime()));
        int i = map.addUserByMap(user);
        if(i>0){
            sqlSession.commit();
            System.out.println("添加成功,影响"+i+"行");
        }
        sqlSession.close();
    }

Map传递参数,直接在sql中取出key即可!【parameterType="map"】

对象传递参数,直接在sql中取对象的属性即可!【parameterType="Object"】

只有一个基本类型参数的情况下,可以直接在sql中取到(即无须定义传入参数类型)

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

3.6.2 模糊查询

模糊查询怎么写?

1、Java代码执行的时候,传递通配符%%

List<User> userList = mapper.getLikeUser("%张%");

2、在sql拼接中使用通配符!

select * from mybatis.user where name like "%"#{value}"%"
  • 但需要注意的是,在sql拼接种可能会带来sql注入问题,可能会给系统带来一些安全性问题

04 配置解析

4.1 核心配置文件

  • mybatis-config.xml
  • MyBatis的配置文件包含了会深深影响Mybatis新闻的设置和属性信息

4.2 环境配置(Enviroments)

  • MyBatis 可以配置成适应多种环境

  • 不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

  • Mybatis的默认事务管理器就是JDBC,连接池:POOLED

4.3 属性(properties)

我们可以通过properties属性来实现引用配置文件。

这些属性都是可外部配置且可动态替换的,既可以在典型的Java属性文件中配置,亦可通过properties元素的子元素来传递。【db.properties】

编写一个配置文件

db.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username = root
password = 12345

在核心配置文件中引入,但需要注意

    <!--引入外部配置文件-->
    <properties resource="db.properties"></properties>
  • 可以直接引入外部文件
  • 可以在xml中增加一些属性配置
  • 如果外部文件和xml中有对同一个字段进行配置,优先使用外部配置文件的!

4.4 类型别名(typeAliases)

  • 类型别名可为 Java 类型设置一个缩写名字。

  • 它仅用于 XML 配置,意在降低冗余的全限定类名书写。

        <typeAliases>
            <typeAlias alias="User" type="com.wu.pojo.User"/>
        </typeAliases>
    
  • 也可以指定一个包名,Mybatis会在包名下面搜索需要的Java Bean,然后使用 Bean 的首字母小写的非限定类名来作为它的别名,或者直接使用注解作为其别名

        <typeAliases>
            <!--<typeAlias alias="User" type="com.wu.pojo.User"/>-->
            <package name="com.wu.pojo"/>
        </typeAliases>
    

    在实体类比较少的时候,使用第一种方式。

    如果实体类十分多,建议使用第二种方式。

    第一种可以自定义别名;第二种则不行,除非使用@Alias注解,例如:

    @Alias("user")
    public class User{
        
    }
    

4.5 设置(Settings)

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

比较重要的设置:

4.6 其他设置

  • typeHandlers(类型处理器)
  • objectFactory(对象工厂)
  • plugins插件
    • mybatis-generator-core
    • mybatis-plus
    • 通用mapper

4.7 映射器(mappers)

MapperRegistry:注册绑定我们的Mapper文件;

方式一:使用相对于类路径的资源引用

 <!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册!-->
 <mappers>
       <!-- <mapper resource="org/mybatis/example/BlogMapper.xml"/>-->
        <mapper resource="com/wu/dao/UserMapper.xml"/>
 </mappers>

方式二:使用完全限定资源定位符(URL)

    <!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册!-->
    <mappers>
        <!--<mapper resource="org/mybatis/example/BlogMapper.xml"/>-->
        <!--<mapper resource="com/wu/dao/UserMapper.xml"/>-->
        <mapper class="com.wu.dao.UserMapper"></mapper>
    </mappers>

方式三:将包内的映射器接口全部注册为映射器

    <!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册!-->
    <mappers>
        <!--<mapper resource="org/mybatis/example/BlogMapper.xml"/>-->
        <!--<mapper resource="com/wu/dao/UserMapper.xml"/>-->
        <!--<mapper class="com.wu.dao.UserMapper"></mapper>-->
        <package name="com.wu.dao"/>
    </mappers>

但需要注意的是,方式二和方式三有两个需要注意的地方:

  • Interface类文件必须和成对的Mapper配置文件同名
  • Interface文件和它配对的Mapper文件必须在同一个包下

4.8 生命周期和作用域

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

SqlSessionFactoryBuilder

  • 一旦创建了SqlSessionFactoryBuilder,就不再需要;
  • 因此作为局部变量

SqlSessionFactory:

  • 可以想象为数据库连接池
  • SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃她或重新创建另一个实例。

05 ResultMap结果集映射

5.1 问题

前面所述实体类的各个属性名称和数据库字段是一一对应的,因此输出的结果都是正常的。

如果对应不上会发生什么?比如将pwd改成password?

结果很明显,这个字段的信息读不出来。

回看一下mapper中编写的sql语句

 select * from mybatis.user

实际上星号部分省略了

 select id,name,pwd,createtime,modifytime from mybatis.user

因此,这个字段名取出后进行映射时自然找不到password名的字段。

5.2 解决方法一(修改sql语句)

解决这个问题有两种常见方法,第一种就是修改语句,给数据库字段pwd取别名。

select id,name,pwd as password,createtime,modifytime from mybatis.user

运行后发现,确实可以取出来:

但这个方法并不好,原因在于如果sql语句较多,就需要每一个都配置相关的别名,会极大增加工作量。

5.3 解决方法二(使用ResultMap映射集)

在Mapper文件中配置resultMap(注意各个部分的顺序问题!)

   <resultMap id="UserMap" type="User">
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="pwd" property="password"/>
        <result column="createtime" property="createTime"/>
        <result column="modifytime" property="modifyTime"/>
    </resultMap>

column指的是数据库的字段,property指的是对象中的属性名

注意,除了配置resultmap外,还有一处需要修改:

红框圈出部分原来是resultType,再使用结果集映射后需要换为resultMap

  • resultmap元素是mybatis中最重要最强大的元素
  • resultmap的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的雨具只需要描述它们之间的关系就行了
  • ResultMap的最优秀之处在于,虽然你已经对他相当了解了,但是根本就不需要现实的用到它们。

06 日志

6.1 日志工厂

如果一个数据库操作出现了异常,需要人为排错,日志就是非常好的帮手。

曾经:debug、sout

现在:日志工厂

  • SLF4J
  • LOG4J(3.5.9 起废弃) (重点)
  • LOG4J2 (重点)
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING (重点)
  • NO_LOGGING

在mybatis中具体使用哪一种日志,在config.xml文件中配置

注意:还记得前面说的配置顺序问题吗,需要注意!

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

  • 可以看到,黄色部分是mybatis打开JDBC连接,以及创建数据库连接的过程,同时将自动提交设置为否。
  • 红框部分包含所执行的sql语句以及在数据库中的查询结果
  • 红框和蓝框间是查询结果
  • 蓝框是执行完sql后一些设置,包括重新开启自动提交以及断开JDBC连接

6.2 LOG4J

什么是Log4j?

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件等等。
  • 我们也可以控制每一条日志的输出格式;
  • 通过定义每一条日志信息的级别,可以使我们更加细致的控制日志的生成过程。
  • 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码

如何快速开始?

1、先导入log4j的jar包

 <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <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/wu.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{yyyy-MM-dd}][%c]%m%n


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

3、配置log4j为日志的实现

 <settings>
        <setting name="logImpl" value="LOG4J"/>
 </settings>

如何使用日志?

  • 在要使用Log4j的类中,导入包import org.apache.log4j.Logger

  • 创建日志对象,参数为当前类的class

    static  Logger logger = Logger.getLogger(XXX.class);
    
  • 日志级别

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

07 分页

7.1 使用Limit分页

思考:为什么要分页?

  • 减少数据的处理量,提高速度

使用Limit分页

SELECT * FROM `user` limit startIndex,pageSize;

使用Mybatis实现分页 ,核心SQL

1、接口

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

2、Mapper.xml

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

3、编写测试方法

 @Test
    public void testPage(){
        SqlSession sqlSession = MybatisUtils.getsqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String,Integer> map = new HashMap<String,Integer>();
        map.put("startIndex",0);
        map.put("pageSize",2);
        List<User> userByLimit = mapper.getUserByLimit(map);
        for (User user : userByLimit) {
            System.out.println(user);
        }
        sqlSession.close();
    }

7.2 使用RowBounds分页

不再使用sql实现分页,使用一个对象实现分类。

新建一个RowBounds对象,然后传入两个参数,分别是偏差(起始位=偏差+1)和条数限制

RowBounds bounds = new RowBounds(1,2);

接口:

List<User> getUserByRowBounds();

mapper.xml:

    <select id="getUserByRowBounds" resultMap="UserMap">
        select * from mybatis.user
    </select>

测试:

 @Test
    public void testRowBounds(){
        SqlSession sqlSession = MybatisUtils.getsqlSession();
        /*新建bounds对象*/
        RowBounds bounds = new RowBounds(1,2);

        /*通过java代码层面实现分页*/
        List<User> userlist = sqlSession.selectList("com.wu.mapper.UserMapper.getUserByRowBounds",null,bounds);
        for (User user : userlist) {
            System.out.println(user);
        }
        sqlSession.close();
    }

7.3 分页插件

08 使用注解开发

8.1 面向接口编程

  • 学习Java,相比于c语言,一个比较大的区别在于编程思路上。Java是一门面向对象的编程语言,同时随着对架构的学习,也知道了包括接口等其他知识。在真正开发中,相比于面向对象,大多数时候人们会选择面向接口编程
  • 根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,开发人员遵守共同的标准,使得开发变得容易,规范性更好
  • 在一个面向对象的系统中,系统的各种功能时由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对于系统设计人员来讲就并不重要。
  • 但与此同时,各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初便是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。

关于接口的理解

  • 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离
  • 接口的本身反映了系统设计人员对系统的抽象理解
  • 接口应有2类:
    • 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class)
    • 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface)
  • 一个个体有可能有多个抽象面。抽象体与抽象面是有区别的。

三个面向的区别

  • 面相对象是指,我们考虑问题时,以对象为单位,考虑它的属性和方法
  • 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现。
  • 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题。更多的体现就是对系统整体的架构的思考。

8.2 使用注解开发

也就是说,不需要配置xml实现接口中的sql,直接在接口文件中使用注解编写sql。

接口:

    @Select("select * from user")
    List<User> getUserList();

修改映射文件配置:

 <mappers>
        <!--<mapper resource="org/mybatis/example/BlogMapper.xml"/>-->
        <!--<mapper resource="com/wu/mapper/UserMapper.xml"/>-->
        <!--<mapper class="com.wu.dao.UserMapper"></mapper>-->
        <!--<package name="com.wu.dao"/>-->
        <mapper class="wu.mapper.UserMapper"></mapper>
    </mappers>

编写测试方法:

 public void test(){
        SqlSession sqlSession = MybatisUtils.getsqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

​ 但是可以发现,由于先前更改了实体类中的pwd为password,因此在采取注解编程时,就无法采取在xml中配置结果集映射的方式。使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让本就复杂的 SQL 语句更加混乱不堪。 因此,如果需要做一些很复杂的操作,最好用 XML 来映射语句。

本质:反射机制!

底层:动态代理!

8.3 Mybatis的详细执行流程(暂缺,后续补齐)

8.4 CRUD

首先,为了方便起见,在创建sqlsession时便设置自动提交事务

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

编写接口,用注解实现增删改查

@Select("select * from user")
    List<User> getUserList();


    /*@Param 如果方法存在多个参数,则所有的参数前面必须加上@Param*/
    @Select("select * from user where id = #{id}")
    User getUserById(@Param("id") int id /*,@Param("name") String name*/);

    @Insert("insert into user(id,name,pwd,createtime,modifytime) values(#{id},#{name},#{password},#{createTime},#{modifyTime})")
    int addUser(User user);


    @Update("update `user` set name = #{name} , pwd = #{password} , createtime = #{createTime} , modifytime = #{modifyTime} where id = #{id}")
    int updateUser(User user);


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

编写测试类,验证相关功能

[注意,每新建一个mapper,都要绑定相关的接口文件]

对于多个mapper.xml文件,可以在前面采取*方式进行通配

<mapper resource="com/wu/mapper/*Mapper.xml"/>
@Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getsqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
/*        List<User> userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }*/
/*        User user = mapper.getUserById(1);*/
        User user = new User();
        user.setId(7);
        user.setName("张恩普");
        user.setPassword("123456");
        user.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        int i = mapper.addUser(user);
        if(i>0) {
            System.out.println("添加成功!影响"+i+"行");
        }
        sqlSession.close();
    }


    @Test
    public void test2(){
        SqlSession sqlSession = MybatisUtils.getsqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user1 = mapper.getUserById(4);
        User user2 = new User(4,"刘天博","987654321", user1.getCreateTime(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date().getTime()));
        int i = mapper.updateUser(user2);
        if (i>0){
            System.out.println("修改完成,影响"+i+"行");
        }
        sqlSession.close();
    }

    @Test
    public void test3(){
        SqlSession sqlSession = MybatisUtils.getsqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int i = mapper.deleteUser(5);
        if(i>0){
            System.out.println("修改完成,影响"+i+"行");
        }
        sqlSession.close();
    }

8.5 Param注解

关于@Param()注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以忽略,但是建议大家都加上
  • 我们在SQL中引用的就是我们这里的@Param()中设定的属性名!

09 Lombok

9.1 什么是lombok

  • 官网英文介绍:
  Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
  Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.
  • 翻译一下:

    Lombok项目是一个java库,它可以自动插入你的编辑器和构造工具,从而实现简化代码和提高java程序的趣味。使用lombk将让你不需要再另写一个getter或setter方法。使用一个注释,你的类就将有一个完整功能的构造器,同时还可以实现包括自动配置你的日志变量等等其他更多功能。

  • 各种注释字段

    @Setter 注解在类或字段,注解在类时为所有字段生成setter方法,注解在字段上时只为该字段生成setter方法。
    @Getter 使用方法同上,区别在于生成的是getter方法。
    @ToString 注解在类,添加toString方法。
    @EqualsAndHashCode 注解在类,生成hashCode和equals方法。
    @NoArgsConstructor 注解在类,生成无参的构造方法。
    @RequiredArgsConstructor 注解在类,为类中需要特殊处理的字段生成构造方法,比如final和被@NonNull注解的字段。
    @AllArgsConstructor 注解在类,生成包含类中所有字段的构造方法。

    @Data 注解在类,生成setter/getter、equals、canEqual、hashCode、toString、无参构造方法,如为final属性,则不会为该属性生成setter方法。
    @Slf4j 注解在类,生成log变量,严格意义来说是常量。private static final Logger log = LoggerFactory.getLogger(UserController.class);

  • 使用步骤:

    • 在IDEA中安装Lombok插件

    • 在项目中导入lombok的jar包

      <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
              <dependency>
                  <groupId>org.projectlombok</groupId>
                  <artifactId>lombok</artifactId>
                  <version>1.18.24</version>
              </dependency>        
      
    • 在实体类中使用lombok

      @Data
      @AllArgsConstructor
      public class User {
          private Integer id;
      
          private String name;
      
          private String password;
      
          private String createTime;
      
          private String modifyTime;
      
      
      }
      
    • 在pojo的user类添加@Data后:

10 复杂查询环境(多对一处理和一对多处理)

10.1 测试环境搭建

  • 数据库建表

    CREATE TABLE `teacher` (
      `id` INT(10) NOT NULL,
      `name` VARCHAR(30) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8;
    
    INSERT INTO teacher(`id`, `name`) VALUES (1, '吴老师'); 
    INSERT INTO teacher(`id`, `name`) VALUES (2, '袁老师'); 
    
    CREATE TABLE `student` (
      `id` INT(10) NOT NULL,
      `name` VARCHAR(30) DEFAULT NULL,
      `tid` INT(10) DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `fktid` (`tid`),
      CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8;
    
    INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1'); 
    INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1'); 
    INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1'); 
    INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '2'); 
    INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '2');
    

  • 导入lombok(具体操作见第9章)

  • 新建实体类Teacher和Student

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Teacher {
    
        private int id;
    
        private String name;
        
    }
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Student {
    
        private int id;
    
        private String name;
    
        /*学生需要关联一个老师*/
        private Teacher teacher;
        
    }
    
  • 在dao文件下建立Mapper接口以及Mapper.xml文件

  • 在核心配置文件中绑定注册Mapper接口或者文件(我这里给出两种,要么用包定义,要么用下面那两个去调Mapper.xml)

  • 测试一下是否能够成功查询

10.2 多对一处理

  • 首先在数据库中尝试实现查询学生和关联老师姓名:

    select s.id,s.name,t.name from student s ,teacher t where s.tid=t.id;
    

  • 但是,这样的sql放到mybatis中却并不好使。

     <select id="getStudent" resultType="student">
            select s.id,s.name,t.name from student s ,teacher t where s.tid=t.id;
        </select>
    

很简单,因为在数据库中查不到teacher属性的数据。因此查出来为空很好理解

  • 解决办法:
    • 按照查询嵌套处理
    • 按照结果嵌套处理

10.2.1 按照查询嵌套处理

    <!--
    思路:
    查询所有的学生信息
    根据查询出来的学生的tid,寻找对应的老师
    方式一:按照查询嵌套处理
    -->
    
    <select id="getStudent1" resultMap="StudentTeacher">
       select * from student
    </select>

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

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

10.2.2 按照结果嵌套处理

<!--
       思路二:
       直接在查询的结果中,将student中teacher的名字属性映射到teacher表的name上不就行了?
    -->

    <select id="getStudent2" resultMap="StudentTeacher2">
       select s.id sid,s.name sname,t.id tid ,t.name tname from student s ,teacher t where s.tid=t.id;
    </select>

    <resultMap id="StudentTeacher2" type="student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <!--复杂的属性,我们需要单独处理 对象association 集合collection-->
        <association property="teacher" javaType="Teacher">
            <result property="id" column="tid"/>
            <result property="name" column="tname"/>
        </association>
    </resultMap>

回顾Mysql多对一查询方式:

  • 子查询
  • 联表查询

10.3 一对多处理

  • 环境搭建和10.1类似,但是需要适当修改实体类

    public class Student {
    
        private int id;
    
        private String name;
        
        private int tid;
    
    }
    
    public class Teacher {
    
        private int id;
    
        private String name;
    
        /*一个老师关联多个学生*/
        private List<Student> studentList;
    
    }
    

10.3.1 按照结果嵌套处理

首先梳理一下思路,按照结果嵌套处理,和10.2.2一样,就是只查询一次,然后在查询过程中配置好映射关系即可。

 <!--按结果嵌套查询-->
    <resultMap id="TeacherStudent1" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--针对复杂的属性,我们需要单独处理 对象:association 集合:collection
        javaType="" 指定属性的类型
        集合中的泛型信息,使用ofType获取
        -->
        <collection property="student" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>
Teacher getTeacher1(@Param("tid") int id);

10.3.2 按照查询嵌套处理

​ 相比于按照结果嵌套查询处理,按照查询嵌套处理会出现多次查询,然后对映射关系的配置相比之下略微简单。但注意此时在collection中需要额外配置许多其它参数,而且实际上在对映射关系的理解上更加复杂。

    <!--按查询嵌套处理-->
    <select id="getTeacher2" resultMap="TeacherStudent2">
        select * from teacher where id = #{tid}
    </select>
    <resultMap id="TeacherStudent2" type="Teacher">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <collection property="student" column = "id" javaType="ArrayList" ofType="Student" select="getStudent"/>
    </resultMap>
    <select id="getStudent" resultType="Student">
        select * from student where tid = #{id}
    </select>
Teacher getTeacher2(@Param("tid") int id);

10.4 总结

1、关联-association【多对一】

2、集合-collection【一对多】

3、javaType & ofType

    1. JavaType 用来指定实体类中属性的类型
    1. ofType 用来指定映射到List或者集合中的pojo类型,是在使用泛型时对所传内容的类型进行约束

4、注意点

  • 保证SQL可读性,尽量保证通俗易懂
  • 注意一对多和多对一中,属性名和字段的问题
  • 如果问题不好排查错误,可以使用日志,建议使用Log4j

面试高频:

  • Mysql引擎
  • InnoDB底层原理
  • 索引
  • 索引优化!

11 动态SQL

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

动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis 显著地提升了这一特性的易用性。 -Mybatis官网

if

choose(when,otherwise)

trim(where,set)

foreach

新建一个工程用于接下来学习(导入jar包和修改配置文件略):

  1. 新建一张表
CREATE TABLE `blog`(
	`id` VARCHAR(50) NOT NULL COMMENT '博客id',
	`title` varchar(100) NOT NULL COMMENT '博客标题',
	`author` varchar(30) NOT NULL COMMENT '博客作者',
	`create_time` datetime NOT NULL COMMENT '创建时间',
	`views` int(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8;
  1. 编写实体类
@Data
public class Blog {

    private String id;

    private String title;


    private String author;

    private Date createTime;

    private int views;
    
}
  1. 启用驼峰命名映射
    <settings>
        <!--是否开启驼峰命名自动映射-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
  1. 编写测试方法写入数据
    //插入数据
    int addBook(Blog blog);
    <insert id="addBook" parameterType="blog">
        insert into mybatis.blog (id,title,author,create_time,views)
        Values (#{id},#{title},#{author},#{createTime},#{views});
    </insert>
@Test
    public void addBlogTest(){
        SqlSession sqlSession = MybatisUtils.getsqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Blog blog = new Blog();

        blog.setId(IdUtils.getId());
        blog.setTitle("Mybatis");
        blog.setAuthor("wutong");
        blog.setCreateTime(new Date());
        blog.setViews(10);

        int i = mapper.addBook(blog);


        blog.setId(IdUtils.getId());
        blog.setTitle("Java");
        blog.setAuthor("wutong");
        blog.setViews(100);
        i+=mapper.addBook(blog);

        blog.setId(IdUtils.getId());
        blog.setTitle("Spring");
        blog.setAuthor("tianbo");
        blog.setViews(1000);
        i+= mapper.addBook(blog);

        blog.setId(IdUtils.getId());
        blog.setTitle("微服务");
        blog.setAuthor("jibo");
        blog.setViews(9999);
        i+=mapper.addBook(blog);

        System.out.println("执行完成!影响"+i+"行");
        sqlSession.close();
    }

11.1 IF使用

利用传入的map内的值来判断是否增加如下的条件语句。

    <select id="queryBlogIf" parameterType="map" 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>

思考:为什么要加入"1=1"这种恒等式?

这样做的目的是在sql进行拼接时,不会出现由于前面没有其他条件直接出现"where and"的情况,致使sql语句报错。使用1=1将使得其他额外查询条件采取统一的 "and+条件"的格式。当然也有别的解决方法,如使用11.3中的where语句。

11.2 Choose(when,otherwise)

Choose配合when使用更加近似于Java中的switch case语句,看下面这个例子:

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

注意,当传入的条件从上到下进入一个when后,就不会再走更下面的的when,即使条件同样满足。(类似java的break)

11.3 Trim(where,set)

11.3.1 where

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

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

大白话就是,如果只有一个查询条件,会自动去掉条件前面的and。如果子句前面有and/or,而且前面无其他条件时,也会去掉。

如果写成下面这种的,也对。但注意,or和and只能多不能少。如果少了会出现报错!

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

11.3.2 set

<update id="updateBlog" parameterType="blog">
        update mybatis.blog
        <set>
             <if test="title!=null">
                 title = #{title},
             </if>
            <if test="views!=0">
                views = #{views},
            </if>
        </set>
        where author = #{author}
    </update>
    @Test
    public void test4(){
        SqlSession sqlSession = MybatisUtils.getsqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Blog blog = new Blog();
        /*blog.setViews(10001);*/
        blog.setTitle("学习神经网络");
        blog.setAuthor("jibo");
        int i = mapper.updateBlog(blog);
        if(i>0){
            System.out.println("执行完成!影响"+i+"行");
        }
        sqlSession.close();
    }

所谓的动态sql,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码。

if

where ,set,choose,when

11.4 SQL片段(可插拔脚本)和Foreach

11.4.1 SQL片段

有的时候,我们可能会讲一些功能的部分抽取出来,方便复用!

  1. 使用SQL标签抽取公共的部分

     <sql id="testSqlPart">
            <if test="title!=null">
                and title = #{title}
            </if>
            <if test="author!=null">
                and author = #{author}
            </if>
        </sql>
    
  2. 在需要使用的地方使用include标签引用即可

    <select id="queryBlogIf" parameterType="map" resultType="blog">
            select * from mybatis.blog
            <where>
                <include refid="testSqlPart"></include>
            </where>
        </select>
    
  • 注意事项:
    • 最好基于单表来定义SQL片段!
    • SQL片段内不要存在where标签,where放在主体内

11.4.2 Foreach

<select id="queryBlogForeach" parameterType="map" 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 test6(){
        SqlSession sqlSession = MybatisUtils.getsqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();

        ArrayList< String> ids = new ArrayList<String>();
        ids.add("2f49a219363a49fd9714697b342db31a");
        map.put("ids",ids);
        List<Blog> blogs = mapper.queryBlogForeach(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

动态SQL就是在拼接SQL语句,我们主要保证SQL的 正确性,按照SQL的格式,去排列组合即可

建议:

  • 先在Mysql中写出完整的SQL再对应修改成为我们的动态SQL实现通用即可!

12 缓存

12.1简介

1、什么是缓存(Cache)

  • 存在内存中的临时数据
  • 将用户经常查询的数据放在缓存(内存)中,用户查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决高并发系统的性能问题。

2、为什么使用缓存?

  • 减少和数据库的交互次数,减少系统开销,提高系统效率。

3、什么样的数据能使用缓存?

  • 经常查询并且不经常改变的数据。

12.2 Mybatis缓存

  • Mybatis包含一个非常强大的查询缓存特性,它可以非常方便的定制和配置缓存。缓存可以极大的提升查询效率。
  • Mybatis系统中默认定义了两级缓存:一级缓存二级缓存
    • 默认情况下,只有一级缓存开启。(sqlsession级别的缓存,也称为本地缓存。一旦关闭sqlsession,则缓存内容丢失。)
    • 二级缓存需要手动开启和配置,其是基于namespace级别的缓存。
    • 为了提高扩展性,Mybatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存。

12.3 一级缓存

  • 一级缓存也叫本地缓存:
    • 与数据库同一次会话期间查询到的数据会放在本地缓存中。
    • 以后如果需要获取想用的数据,则直接从缓存中拿,没必要再去查询数据库。

测试步骤:

  • 1、开启日志

    <settings>
            <!--是否开启驼峰命名自动映射-->
            <setting name="mapUnderscoreToCamelCase" value="true"/>
            <!--标准日志工厂配置-->
            <setting name="logImpl" value="STDOUT_LOGGING"/>
        </settings>
    
  • 2、测试在一个session中查询两次相同的sql。

    public void test1(){
            SqlSession sqlSession = MybatisUtils.getsqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            Integer id = 1;
            User user1 = mapper.queryUserById(id);
            System.out.println(user1);
            Integer id2 = 1;
            System.out.println("=====================");
            User user2 = mapper.queryUserById(id2);
            System.out.println(user2);
            System.out.println("=====================");
            System.out.println(user1==user2);
            sqlSession.close();
        }
    
  • 3、查看日志输出

缓存失效的情况:

  1. 增删改操作,可能会改变原来的数据,因此必定会刷新缓存!

  2. 查询不同sql(条件不一致也会失效)

  3. 查询不同的Mapper.xml

  4. 手动清理缓存(操作如下,可以看到会执行两次查询操作)

    sqlSession.clearCache();
    

小结:

  • 一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!

12.4 二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存

  • 工作机制
    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据会被保存到二级缓存中。
    • 新的会话查询信息,就可以从二级缓存中获取内容;
    • 不同的mapper查出的数据会放在自己对应的缓存(map)中;

步骤:

1、开启全局缓存

<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>

注意:虽然系统中默认cacheEnabled是开启状态,但最好还是在mybatis的配置文件中显示的说明,增加代码的可读性

2、在需要使用二级缓存的Mapper.xml文件中添加缓存相关配置(注意前面说过,二级缓存是基于namespace级别的缓存)

 <!--在当前Mapper.xml中使用二级缓存-->
    <cache
         eviction="FIFO"
         flushInterval="60000"
         size="512"
         readOnly="true"
    />

3、测试

 @Test
    public void test4(){
        SqlSession sqlSession = MybatisUtils.getsqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user1 = mapper.queryUserById(1);
        System.out.println(user1);
        sqlSession.close();
        System.out.println("=====================");
        SqlSession sqlSession1 = MybatisUtils.getsqlSession();
        UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
        User user2 = mapper1.queryUserById(1);
        System.out.println(user2);
        sqlSession1.close();
        System.out.println("=====================");
        System.out.println(user1==user2);
    }

问题:如果去除cache 的相关配置,需要对实体类进行序列化操作。

Cause: java.io.NotSerializableException: com.wu.pojo.User

小结:

  • 只要开启了二级缓存,在同一个mapper下就有效
  • 所有的数据仍然会先放在一级缓存中;
  • 只有当会话提交,或者关闭的时候,才会提交到二级缓存中!

12.5 缓存原理

查询顺序:首先进入当前的mapper,看一下二级缓存中有没有相关的结果;

如果有相关的查询结果直接输出,没有的话进入当前的sqlsession,看一下一级缓存有没有。

如果一级缓存还没有,则进行数据库查询操作。并把查询结果存入一级缓存。

如果当前的sqlsession关闭了,则一级缓存会将相关内容存入对应的二级缓存当中。

12.6 自定义缓存-ehcache

Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存

要使用ehcache首先要导入jar包

<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
        <dependency>
            <groupId>org.mybatis.caches</groupId>
            <artifactId>mybatis-ehcache</artifactId>
            <version>1.2.1</version>
        </dependency>

在resource目录中建立一个配置文件ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">

    <!--
       diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
       user.home -用户主目录
       user.dir - 用户当前工作目录
       java.io.tmpdir -默认临时文件路径
    -->
    <diskStore path="./tmpdir/Tmp_EhCache"/>

    <defaultCache
            eternal="false"
            maxElementsInMemory="10000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"/>

    <cache
            name="cloud_user"
            eternal="false"
            maxElementsInMemory="5000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="1800"
            memoryStoreEvictionPolicy="LRU"/>

    <!--
       defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
    -->

    <!--
      name:缓存名称
      maxElementsInMemory:缓存最大数目
      maxElementsOnDisk:硬盘最大缓存个数
      eternal:对象是否永久有效,一旦设置了,timeout将不起作用
      overflowToDisk:是否保存到磁盘,当系统宕机时
      timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:s)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是该对象可以无限期的处于空闲状态
      timeToLiveSeconds:设置对象在失效前允许的存活时间(单位:s)。当对象自从被存放到缓存中后,如果处于缓存中的时间超过了 timeToLiveSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清除。只有当eternal属性为false,该属性才有效。
      diskPersistent:是否缓存虚拟机重启期数据
      diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个cache都应该有自己的一个缓冲区。
      diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认120s。
      memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
      FIFO:first in first out
      LFU,less frequently Used缓存的元素有一个hit属性,表示该缓存的访问频率。如果hit值较低则容易被干掉
      LRU,least recently used 最近最少使用的,缓存的元素有一个时间戳,当缓存的容量满了,二有需要腾出地方给缓存的新元素时,会检查现有缓存中所有元素近期的访问情况。
    -->

</ehcache>

在要使用缓存的mapper中使用type调用

 <!--在当前Mapper.xml中使用二级缓存-->
    <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

但现在主要是用Redis数据库来做缓存!借助K-V键值对来实现调用。

www.htsjk.Com true http://www.htsjk.com/Mysql/47023.html NewsArticle Mybatis小白入门,它支持自定义SQL、 Mybatis-9.28 环境: JDK:1.8 Mysql:8.032 maven:3.9.2 IDEA 回顾: JDBC Mysql JavaSE Maven Junit 01 简介 1.1 什么是MyBatis MyBatis 是一款优秀的持久层框架。 它支持自定...
评论暂时关闭