0%

MyBatis学习笔记

1.MyBatis是什么?

mybatis

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

2.如何获得MyBatis?

  • maven仓库

    1
    2
    3
    4
    5
    6
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
    </dependency>
  • GitHub:https://github.com/mybatis/mybatis-3/releases

  • 中文文档

3.什么是持久层

  • 数据持久化
    1. 概念:持久化就是将程序的数据在持久状态和瞬时状态转化的过程
    2. 内存:断电即失
    3. 持久化的方式:数据库(JDBC),IO文件持久化
  • 为什么要持久化?
    • 有一些对象不能让它丢失,因为内存断电即失的特性,需要数据持久化
    • 内存太贵了
  • 持久层
    • Dao层、Service层、Controller层
    • 完成持久化工作的代码块
    • 层是界限十分明显的

4. 为什么需要MyBatis?

  • 帮助程序员将数据存入数据库中
  • 传统的JDBC代码太复杂了
  • 方便,简化,框架,自动化
  • 优点:
    • 简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件。易于学习,易于使用。通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
    • 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
    • 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
    • 提供映射标签,支持对象与数据库的ORM字段关系映射。
    • 提供对象关系映射标签,支持对象关系组建维护。
    • 提供xml标签,支持编写动态sql。

5.第一个MyBatis程序

  • 思路:搭建环境 –> 导入MyBatis -> 编写代码 –> 测试!

  • 搭建环境

    搭建数据库

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    CREATE DATABASE mybatis;
    USE mybatis;

    CREATE TABLE user(
    id INT(20) NOT NULL PRIMARY KEY,
    name VARCHAR(20) DEFAULT NULL,
    pwd VARCHAR(20) DEFAULT NULL
    )ENGINE=INNODB DEFAULT CHARSET=utf8;

    INSERT INTO user(id, name, pwd) VALUES
    (1, 'mcc', '123456'),
    (2, 'zhangsan', '123456'),
    (3, 'lisi', '123456');
  • 新建项目

    1. 新建一个普通的maven项目

    2. 删除src目录

    3. 编辑pom.xml导入maven依赖

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      <?xml version="1.0" encoding="UTF-8"?>
      <project xmlns="http://maven.apache.org/POM/4.0.0"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>

      <!--父工程-->
      <groupId>org.example</groupId>
      <artifactId>mybatisStudy</artifactId>
      <version>1.0-SNAPSHOT</version>

      <!--导入依赖-->
      <dependencies>
      <!--mysql驱动-->
      <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.32</version>
      </dependency>

      <!--mybatis-->
      <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.2</version>
      </dependency>

      <!--junit-->
      <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
      </dependency>

      </dependencies>

      <properties>
      <maven.compiler.source>9</maven.compiler.source>
      <maven.compiler.target>9</maven.compiler.target>
      </properties>

      </project>
  • 创建一个模块(new module –> maven项目 –> 起名mybatis-01)

    • 可以发现子模块继承了父模块,不需要再导入maven依赖了
    1. 编写mybatis的核心配置文件

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      <?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核心配置文件-->
      <configuration>

      <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/travel?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
      <property name="username" value="root"/>
      <property name="password" value="123456"/>
      </dataSource>
      </environment>
      </environments>

      </configuration>
    2. 编写mybatis工具类

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      // sqlSessionFactory --> sqlSession
      public class MyBatisUtils {
      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){
      e.printStackTrace();
      }
      }

      // 既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
      // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
      public static SqlSession getSqlSession(){
      return sqlSessionFactory.openSession();
      }
      }
    3. 编写代码

      • 实体类

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        40
        41
        42
        43
        44
        45
        46
        47
        48
        49
        50
        package com.mcc.pojo;

        // 实体类
        public class User {
        private int id;
        private String name;
        private String pwd;

        public User() {
        }

        public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
        }

        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;
        }

        @Override
        public String toString() {
        return "User{" +
        "id=" + id +
        ", name='" + name + '\'' +
        ", pwd='" + pwd + '\'' +
        '}';
        }
        }
      • Dao接口

        1
        2
        3
        4
        public interface UserDao {
        public List<User> getUserList();
        }

      • 接口实现类由原来的UserDaoImpl转换为一个Mapper配置文件

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        <?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绑定一个对应的Dao/Mapper接口-->
        <mapper namespace="com.mcc.dao.UserDao">
        <!--select查询语句-->
        <select id="getUserList" resultType="com.mcc.pojo.User">
        select * from travel.user;
        </select>
        </mapper>
    4. 测试

      • 注意点

        1. ```bash
          org.apache.ibatis.binding.BindingException: Type interface com.mcc.dao.UserDao is not known to the MapperRegistry.

          1
          2
          3
          4
          5
          6
          7
          8
          9

          MapperRegistry是什么?

          每一个`Mapper.XML`都需要在Mybatis核心配置文件`resources/mybatis-config.xml`中注册!!!

          ```xml
          <mappers>
          <mapper resource="com/mcc/dao/UserMapper.xml"></mapper>
          </mappers>
        2. ```bash
          java.lang.ExceptionInInitializerError
          Caused by: java.io.IOException: Could not find resource com/mcc/dao/UserMapper.xml

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          28
          29

          这个问题来自于Maven本身,资源过滤问题!!!

          maven由于他的约定大于配置,我们可能遇到写的配置文件,无法被导出或者无法生效的问题,解决方案:

          需要在`pom.xml`中配置

          ```xml
          <!--在build中配置resources,防止资源导出失败的问题-->
          <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>true</filtering>
          </resource>
          </resources>
          </build>
      • Junit测试

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        @Test
        public void test(){
        // 第一步,获得sqlSession对象
        SqlSession sqlSession = MyBatisUtils.getSqlSession();

        // 方式一:getMapper
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> userList = mapper.getUserList();

        for(User user:userList){
        System.out.println(user);
        }

        // 关闭sqlSession
        sqlSession.close();
        }
      • 可能会遇到的问题

        1. 配置文件没有注册
        2. 绑定接口错误
        3. 方法名不对
        4. 返回类型不对
        5. Maven导出资源问题

6.CRUD

  1. namespace

    Mapper配置文件中的namespace的包名要和Dao/Mapper接口名称一致!

  2. select

    • 选择、查询语句;
      1. id:对应namespace中的方法名
      2. resultType:Sql语句执行的返回值
      3. paramterType:参数类型
  3. insert

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    // 增删改需要提交事务
    SqlSession sqlSession = MyBatisUtils.getSqlSession();
    User user = new User(5, "liumei", "123456");

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    int res = mapper.addUser(user);
    List<User> userList = mapper.getUserList();
    if (res > 0){
    System.out.println("插入成功!");
    }

    // 提交事务
    sqlSession.commit();
    sqlSession.close();
  4. update

    1
    2
    3
    4
    5
    6
    <update id="updateUser" parameterType="com.mcc.pojo.User">
    update travel.user
    set name = #{name},
    pwd = #{pwd}
    where id = #{id};
    </update>
  5. delete

    1
    2
    3
    <delete id="deleteUser" parameterType="int">
    delete from travel.user where id = #{id};
    </delete>

7.万能的Map

假设我们的实体类或者数据库中的表的参数或者字段过多,应当考虑使用Map。

1
2
3
<insert id="addUser2" parameterType="">
insert into travel.user (id, name, pwd) values (#{userid}, #{username}, #{userpwd});
</insert>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
public void addUser2Test(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
Map<String, Object> mapper = new HashMap<>();
mapper.put("userid", 6);
mapper.put("username", "hello");
mapper.put("userpwd", "52345");

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int res = userMapper.addUser2(mapper);
if (res > 0){
System.out.println("添加成功!");
}

// 提交事务
sqlSession.commit();
sqlSession.close();
}

Map传递参数,直接在sql中取出key即可! [parameterType=”map”]

对象传递参数,直接在sql中取出对象的属性即可![parameterType=”Object”]

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

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

8.模糊查询

  1. 模糊查询怎么写?

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

      1
      List<User> userList = mapper.getUserLike("%李%");
    2. 在sql拼接中使用通配符

      1
      select * from travel.user where name like "%"#{value}"%"

9.配置解析

  1. 核心配置文件mybatis-config.xml

  2. environments(环境配置)

    1. MyBatis 可以配置成适应多种环境
    2. 尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
    3. MyBatis默认的事务管理器就是JDBC,连接池:JDBC
  3. properties(属性)

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

    • 这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。

      1. 编写一个配置文件db.properties
      1
      2
      3
      4
      driver=com.mysql.jdbc.Driver
      url=jdbc:mysql://localhost:3306/travel?useSSL=true&useUnicode=true&characterEncoding=UTF-8
      username=root
      password=123456
      • 在核心配置文件中引用(在xml中,所有标签都可以规定顺序)

        1
        2
        3
        4
        5
        <!--引入外部配置文件-->
        <properties resource="db.properties">
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
        </properties>
      • 可以直接引入外部文件

      • 可以在其中增加一些属性配置

      • 如果两个文件有同一字段,优先使用外部配置文件

  4. typeAliases(类型别名)

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

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

      1
      2
      3
      4
      <!--可以给实体类起别名-->
      <typeAliases>
      <typeAlias type="com.mcc.pojo.User" alias="User"/>
      </typeAliases>
    • 也可以指定一个包名,MyBatis会在包名下面搜索需要的Java Bean,比如:

      扫描实体类的包,它的默认别名就为这个类的首字母小写

    • 注意:

      1. 实体类少的时候,使用第一种方式
      2. 实体类非常多,建议使用第二种方式(如果需要改实体类名字,在实体类上增加注解)
  5. settings(设置)

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

      image-20220825191144403

  6. mappers(映射器)

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

    • 方式一【推荐使用】

      1
      2
      3
      4
      <!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册!!!-->
      <mappers>
      <mapper resource="com/mcc/dao/UserMapper.xml"></mapper>
      </mappers>
    • 方式二:使用class文件绑定注册

      1
      2
      3
      4
      <!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册!!!-->
      <mappers>
      <mapper class="com.mcc.dao.UserMapper"></mapper>
      </mappers>
    • 方式三:使用扫描包进行注入绑定

      1
      2
      3
      4
      <!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册!!!-->
      <mappers>
      <package name="com.mcc.dao"/>
      </mappers>
    • 注意点:

      1. 接口和它的Mapper配置文件必须同名(文件后缀名可以不一样)
      2. 接口和它的Mapper配置文件必须在同一包下!(方法二、三)

10.作用域(Scope)和生命周期

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

    1. SqlSessionFactoryBuilder

      这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。 因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)

    2. SqlSessionFactory

      • 类似于数据库连接池

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

    3. SqlSession

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

11.解决属性名和字段名不一致的问题

数据库中的字段

image-20220827155609464

新建一个项目,拷贝之前的,测试实体类字段不一致的情况

1
2
3
4
5
public class User {
private int id;
private String name;
private String password;
}

测试出现问题

image-20220827155750351

1
2
3
// select * from travel.user where id = #{id};
// 类型处理器
// select id,name,pwd from travel.user where id = #{id};

解决方法:

  1. 起别名

    1
    2
    3
    <select id="getUserById" resultType="com.mcc.pojo.User" parameterType="int">
    select id,name,pwd as password from travel.user where id = #{id};
    </select>
  2. resultMap:结果集映射

    1
    2
    id name pwd
    id name password
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <!--结果集映射-->
    <resultMap id="UserMap" type="user">
    <!--column数据库中的字段,property实体类中的属性-->
    <result column="id" property="id"></result>
    <result column="name" property="name"></result>
    <result column="pwd" property="password"></result>
    </resultMap>

    <select id="getUserById" resultMap="UserMap" parameterType="int">
    select id,name,pwd from travel.user where id = #{id};
    </select>
    • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
    • 没有一个需要显式配置 ResultMap,这就是 ResultMap 的优秀之处——你完全可以不用显式地配置它们。

12.日志

  1. 日志工厂

    • 如果一个数据库操作,出现了异常,我们需要排错,日志就是最好的助手!

    • 曾经:sout、debug

    • 现在:日志工厂

      image-20220827172335937

      • SLF4J
      • LOG4J 【掌握】
      • LOG4J2
      • JDK_LOGGING
      • COMMONS_LOGGING
      • STDOUT_LOGGING 【掌握】
      • NO_LOGGING
    • 在mybatis中具体使用哪一个日志实现,在mybatis-config.xml设置中设定

      1
      2
      3
      <settings>
      <setting name="logImpl" value="STDOUT_LOGGING"/>
      </settings>

      image-20220827175253937

  2. Log4j

    1. 什么是Log4j:

      1. Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件

      2. 我们也可以控制每一条日志的输出格式

      3. 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程

      4. 这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

    2. 使用Log4j的方法

      1. pom.xml导入包

        1
        2
        3
        4
        5
        6
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
        </dependency>
      2. 配置log4j.properties

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        ### set log levels ###
        log4j.rootLogger=DEBUG,console,logFile
        log4j.additivity.org.apache=true

        # 控制台(console)
        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

        # 日志文件(logFile)
        log4j.appender.logFile=org.apache.log4j.FileAppender
        log4j.appender.logFile.File=./logs/log.log4j
        log4j.appender.logFile.MaxFileSize=10mb
        log4j.appender.logFile.Threshold=DEBUG
        log4j.appender.logFile.layout=org.apache.log4j.PatternLayout
        log4j.appender.logFile.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

        # 日志输出级别
        log4j.logger.rog.mybatis=DEBUG
        log4j.logger.java.sql=DEBUG
        log4j.logger.java.sql.Statement=DEBUG
        log4j.logger.java.sql.ResultSet=DEBUG
        log4j.logger.sql.PreparedStatement=DEBUG
      3. mybatis-config.xml文件中配置Log4j为日志的实现

        1
        2
        3
        <settings>
        <setting name="logImpl" value="LOG4J"/>
        </settings>
      4. Log4j的使用,直接测试运行刚才的查询

        • 简单使用

          1. 在要使用Log4j的类中,导入包

            1
            import org.apache.log4j.Logger;
          2. 日志对象,参数为当前类的class

            1
            static Logger logger = Logger.getLogger(UserMapperTest.class);
          3. 日志级别

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

    13.分页

    思考:为什么要分页?

    • 减少数据的处理量

    使用LIMIT分页

    1
    SELECT * FROM user LIMIT startIndex, pageSize; # index从0开始
    • 使用MyBatis实现分页,核心SQL

      1. 接口

        1
        2
        // 分页查询
        List<User> getUserByPage(Map<String, Integer> map);
      2. Mapper.xml

        1
        2
        3
        <select id="getUserByPage" resultMap="UserMap" parameterType="map">
        select * from travel.user limit #{startIndex}, #{pageSize};
        </select>
      3. 测试

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        @Test
        public void getUserByPageTest(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        Map<String, Integer> map = new HashMap<>();
        map.put("startIndex", 0);
        map.put("pageSize", 2);

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userByPage = mapper.getUserByPage(map);

        for(User user:userByPage){
        System.out.println(user);;
        }

        sqlSession.close();
        }
  • RowBounds分页

    Java代码层面实现分页,了解即可

14.使用注解开发

  1. 面向接口编程

    • 在真正的开发中,很多时候我们会选择面向接口编程
      • 根本原因:解耦,可扩展,提高复用。分层开发中,上层不用管具体的实现,大家遵守共同的标准,使得开发更容易,更规范。
    • 关于接口的理解
      • 接口从更深层次的理解,应是定义(规范、约束)与实现(名实分离的原则)的分离
      • 接口的本身反映了系统设计人员对系统的抽象理解
      • 接口有两类:
        1. 对一个个体的抽象,它可对应一个抽象体(abstract class)
        2. 对一个个体某个方面的抽象,即形成一个抽象面(interface)
      • 一个个体有可能有多个抽象面,抽象体与抽象面是有区别的
    • 三个面向区别
      • 面向对象:我们考虑问题时,以对象为单位,考虑其属性以及方法
      • 面向过程:我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑其实现
      • 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构
  2. 使用注解开发

    • 底层实现本质:主要应用反射,底层就是动态代理

    • 注解在接口上实现

      1
      2
      @Select("select * from travel.user")
      List<User> getUsers();
    • 需要在核心配置文件中绑定借口

      1
      2
      3
      4
      <!--绑定接口-->
      <mappers>
      <mapper class="com.mcc.dao.UserMapper"></mapper>
      </mappers>
  3. MyBatis详细执行流程

    img

  4. CRUD

    • 我们可以在工具类的创建的时候实现自动提交事务

      1
      2
      3
      public static SqlSession getSqlSession(){
      return sqlSessionFactory.openSession(true);
      }
    • 编写接口

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    public interface UserMapper {
    @Select("select * from travel.user")
    List<User> getUsers();

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

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

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

    @Delete("delete from user where id=#{id}")
    int deleteUser(@Param("id") int id);
    }
    • 测试类

      注意:我们必须要将接口注册绑定到核心配置文件中

      关于@Param()注解:

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

      ${}#{}区别:

      1. #是将传入的值当做字符串的形式,

        eg: select id,name,age from student where id =#{id}

        当前端把id值1,传入到后台的时候,就相当于 select id,name,age from student where id ='1'.

      2. $是将传入的数据直接显示生成sql语句,仅仅为一个纯碎的 string 替换,在动态 SQL 解析阶段将会进行变量替换。

      eg: select id,name,age from student where id =${id}

      当前端把id值1,传入到后台的时候,就相当于 select id,name,age from student where id = 1.

      1. 使用#可以很大程度上防止sql注入。(语句的拼接)

      2. 但是如果使用在order by 中就需要使用 $.

      3. 在大多数情况下还是经常使用#,但在不同情况下必须使用$.

15.Lombok

16.多对一

  • 多个学生,对应一个老师

    1. 对于学生而言,关联… 多个学生,关联一个老师【多对一】
    2. 对于老师而言,集合,一个老师,有很多学生【一对多】
  • SQL

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    CREATE TABLE `teacher`(
    `id` INT(10) NOT NULL PRIMARY KEY,
    `name` VARCHAR(30) DEFAULT NULL
    )ENGINE=INNODB DEFAULT CHARSET=utf8;

    INSERT INTO `teacher` (`id`, `name`) VALUES (1, "秦老师");

    CREATE TABLE `student`(
    `id` INT(10) NOT NULL PRIMARY KEY,
    `name` varchar(30) DEFAULT NULL,
    `tid` int(10) DEFAULT NULL,
    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), (2, '小红',1), (3, '小张',1), (4, '小李',1), (5, '小王',1);
  • 测试环境搭建

​ 1. 新建实体类Teacher,Student

​ 2. 建立Mapper接口

​ 3. 建立Mapper.xml文件

​ 4. 在核心配置文件中绑定注册Mapper接口或者文件【方式很多,随意写】

​ 5. 测试查询是否成功

  • 按照查询嵌套处理

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <!--
    思路:
    1.查询所有的学生信息
    2.根据查询出的学生的tid,寻找对应的老师

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

    </resultMap>

    <select id="getStudents" resultMap="StudentTeacher">
    select * from student;
    </select>

    <select id="getTeacher" resultType="Teacher">
    select * from teacher where id=#{id};
    </select>
  • 按照结果嵌套处理

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <!--按照结果嵌套处理-->
    <select id="getStudents2" resultMap="StudentTeacher2">
    select s.id sid, s.name sname, 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 property="teacher" javaType="Teacher">
    <result property="name" column="tname"/>
    </association>
    </resultMap>

17.一对多

  • 按照结果嵌套查询

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <!--按结果嵌套查询-->
    <select id="getByID" resultMap="TeacherStudent">
    select s.id sid, s.name sname, t.id tid, t.name tname
    from student s, teacher t
    where s.tid=t.id and t.id=#{tid};
    </select>

    <!--复杂的属性,我们需要单独处理
    对象:association
    集合:collection
    javaType="" 指定属性的类型
    集合中的泛型信息,我们用ofType获取-->

    <resultMap id="TeacherStudent" type="Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>

    <collection property="students" ofType="Student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <result property="tid" column="tid"/>
    </collection>
    </resultMap>
  • 按照查询嵌套处理

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <select id="getByID2" resultMap="TeacherStudent2">
    select * from teacher where id=#{id};
    </select>

    <resultMap id="TeacherStudent2" type="Teacher">
    <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherID" column="id"/>
    </resultMap>

    <select id="getStudentByTeacherID" resultType="Student">
    select * from student where tid=#{tid};
    </select>

小结:

  1. 关联-association 【多对一】
  2. 集合-collection【一对多】
  3. javaType & ofType
    1. javaType用于指定实体类中属性的类型
    2. ofType用于指定映射到List或者集合中的pojo类型,泛型中的约束类型!

注意点:

  1. 保证sql的可读性,尽量保证通俗易懂
  2. 注意一对多、多对一中,属性名和字段的问题
  3. 如果问题不好排查,使用日志

18.动态SQL

  • 定义:动态SQL就是指根据不同的条件生成不同的SQL语句

  • 标签:

    • if
    • choose (when, otherwise)
    • trim (where, set)
    • foreach
  • 搭建环境

    1
    2
    3
    4
    5
    6
    7
    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. 导包

    2. 编写配置文件

    3. 编写实体类

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      package com.mcc.pojo;

      import java.util.Date;

      public class Blog {
      private int id;
      private String title;
      private String author;
      private Date createTime;
      private int views;

      public Blog() {
      }

      public Blog(int id, String title, String author, Date createTime, int views) {
      this.id = id;
      this.title = title;
      this.author = author;
      this.createTime = createTime;
      this.views = views;
      }

      public int getId() {
      return id;
      }

      public void setId(int id) {
      this.id = id;
      }

      public String getTitle() {
      return title;
      }

      public void setTitle(String title) {
      this.title = title;
      }

      public String getAuthor() {
      return author;
      }

      public void setAuthor(String author) {
      this.author = author;
      }

      public Date getCreateTime() {
      return createTime;
      }

      public void setCreateTime(Date createTime) {
      this.createTime = createTime;
      }

      public int getViews() {
      return views;
      }

      public void setViews(int views) {
      this.views = views;
      }

      @Override
      public String toString() {
      return "Blog{" +
      "id=" + id +
      ", title='" + title + '\'' +
      ", author='" + author + '\'' +
      ", createTime=" + createTime +
      ", views=" + views +
      '}';
      }
      }
    4. 编写实体类对应Mapper接口和Mapper.xml文件

  • if

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <select id="queryBlogIF" parameterType="map" resultType="blog">
    select * from blog where 1=1
    <if test="title != null">
    and title = #{title}
    </if>

    <if test="author != null">
    and author = #{author}
    </if>
    </select>
  • choose(when, otherwise)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <select id="queryBlogChoose" parameterType="map" resultType="blog">
    select * from blog where 1=1
    <choose>
    <when test="title != null">
    and title=#{title}
    </when>
    <when test="author != null">
    and author=#{author}
    </when>
    <otherwise>
    order by create_time DESC;
    </otherwise>
    </choose>
    </select>
  • trim、where、set

    MyBatis 有一个简单且适合大多数场景的解决办法。而在其他场景中,可以对其进行自定义以符合需求。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <select id="queryBlogWhere" parameterType="map" resultType="Blog">
    SELECT * FROM BLOG
    <where>
    <if test="title != null">
    title = #{title}
    </if>
    <if test="author != null">
    and author=#{author}
    </if>
    </where>
    </select>

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <update id="updateBlog" parameterType="map">
    update blog
    <set>
    <if test="title!=null">title=#{title},</if>
    <if test="author!=null">author=#{author},</if>
    <if test="views!=null">views=#{views}</if>
    </set>
    where id=#{id};
    </update>
  • 所谓的动态sql,本质还是sql语句,只是我们可以在sql层面去执行一个逻辑代码

  • sql片段

    • 使用sql标签抽取复用的代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <sql id="if-title-author">
    <if test="title != null">
    and title = #{title}
    </if>

    <if test="author != null">
    and author = #{author}
    </if>
    </sql>

    <select id="queryBlogIF" parameterType="map" resultType="blog">
    select * from blog where 1=1
    <include refid="if-title-author"></include>
    </select>
    • 注意:
      1. 最好基于单表定义SQL片段
      2. 不要存在where标签
  • foreach

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <!--传递一个万能的map, map中存在一个集合-->
    <select id="queryBlogForeach" resultType="blog" parameterType="map">
    select *
    from blog
    <where>
    id in
    <foreach item="item" index="index" collection="ids"
    open="(" separator="," close=")">
    #{item}
    </foreach>
    </where>
    </select>

缓存

  • 简介

    • 什么是缓存【cache】?

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

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

    • 什么样的数据使用缓存

      经常查询且不经常改变的数据

  • MyBatis缓存

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

    • 一级缓存也叫本地缓存:每当一个新 session 被创建,MyBatis 就会创建一个与之相关联的本地缓存。任何在 session 执行过的查询结果都会被保存在本地缓存中,所以,当再次执行参数相同的相同查询时,就不需要实际查询数据库了。本地缓存将会在做出修改、事务提交或回滚,以及关闭 session 时清空。

    • 默认开启,只在一次SqlSession中有效,也就是拿到连接和关闭连接之间有效

    • 测试步骤

      1. 开启日志

      2. 测试在一个session中查询两次相同记录

      3. 查看日志输出

        image-20220901162743553

    • 缓存失效的情况

      image-20220901163029019

  • 二级缓存

    • 二级缓存也叫全局缓存,一级缓存作用域太小,所以诞生了二级缓存

    • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存

    • 工作机制

      1. 一个会话查询一条数据,这个数据会被存放在当前会话的一级缓存中
      2. 如果当前会话关闭,会话对应的一级缓存就会消失,我们想要的是,会话关闭后,一级缓存数据被保存到二级缓存中
      3. 新的会话查询信息,就可以从二级缓存中获取内容
      4. 不同的mapper查出的数据会放在自己对应的缓存(map)中
    • 步骤

      1. 开启全局缓存

        1
        2
        <!--显示的开启全局缓存-->
        <setting name="cacheEnabled" value="true"/>
      2. Mapper.xml中添加一条

        1
        <cache/>

        也可以自定义一些参数

        1
        2
        3
        4
        5
        <!--开启二级缓存-->
        <cache eviction="FIFO"
        flushInterval="60000"
        size="512"
        readOnly="true"/>
      3. 测试

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        @Test
        public void findUserByIDTest(){
        SqlSession sqlSession1 = MyBatisUtils.getSqlSession();
        SqlSession sqlSession2 = MyBatisUtils.getSqlSession();
        UserMapper mapper = sqlSession1.getMapper(UserMapper.class);
        UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
        User user = mapper.findUserByID(2);
        System.out.println(user);
        sqlSession1.close();
        System.out.println("======================");

        User user2 = mapper2.findUserByID(2);
        System.out.println(user2);
        System.out.println(user==user2);
        }
  • 缓存原理

    image-20220901170804797

自定义缓存ehcache

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

Redis数据库做缓存 K-V