手把手教你Mybatis(完结篇)

1、什么是mybatis?

在这里插入图片描述

  • MyBatis 是一款优秀的 持久层框架 。

  • 它支持自定义 SQL、存储过程以及高级映射。

  • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

  • MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了[google code](https://baike.baidu.com/item/google code/2346604),并且改名为MyBatis 。

  • 2013年11月迁移到Github

1.1如何获得mybatis?

  • maven仓库:

  • <!- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>
    
    
  • github:https://github.com/mybatis/mybatis-3/releases

  • 中文文档:https://mybatis.org/mybatis-3/zh/index.html

1.2持久化

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

  • 内存:断电及失 把你们

  • 生活:冷藏,如罐头

    为什么要持久化?

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

  • 内存太贵·

1.3持久层

Dao层、service层、Controller层等

  • 完成持久化层的代码块
  • 层界限十分明显

1.4 为什么需要mybatis?

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

​ Spring->SpringMVC->SpringBoot

2、第一个Mybatis程序

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

2.1搭建环境

搭建数据库

`user`CREATE DATABASE mybatis;
SHOW DATABASES;
USE mybatis;
CREATE TABLE USER(
id INT(20) NOT NULL PRIMARY KEY,
NAME  VARCHAR(30) DEFAULT NULL,
psw VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
SHOW TABLES;

INSERT INTO USER(id,NAME,psw)VALUES
(3,'root','Abc123#$'),
(4,'admin','Abc123#$')
SELECT*FROM USER;

新建项目

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

2、删除src目录

3、导入maven依赖

2.2创建一个某块

1、编写mybatis的核心配置文件

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

</configuration>

2、编写mybatis工具类

package com.wangzj.utils;
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;


/  
 * @author wangzhijun
 * @date 2021/6/4
 * @e-mail wangzj_root@163.com
 * @describe SqlSessionFactory -->构建SqlSession
 */
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
//           使用mybatis第一步:获取 SqlSessionFactory对象
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//    既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
//    SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
    public static SqlSession SqlSession(){
        return sqlSessionFactory.openSession();
       
    }
}


2.3编写代码

  • 实体类
package com.wangzj.pojo;

/  
 * @author wangzhijun
 * @date 2021/6/4
 * @e-mail wangzj_root@163.com
 * @describe 实体类
 */
public class User {
    private int id;
    private String name;
    private String psw;

    public User(){
     }

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

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getPsw() {
        return psw;
    }

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

    public void setName(String name) {
        this.name = name;
    }

    public void setPsw(String psw) {
        this.psw = psw;
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", psw='" + psw + '\'' +
                '}';
    }


}

  • Dao接口

    package com.wangzj.dao;
    
    import com.wangzj.pojo.User;
    
    import java.util.List;
    
    public interface UserDao {
        List<User> getUserList();
    }
    
    
  • 接口实现类由原来的DaoUserImplement转化为一个Mapper配置文件

<?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 namespace="com.wangzj.dao.UserDao">
<!--select 查询语句-->
    <select id="getUserList" resultType="com.wangzj.pojo.User">
        select *from mybatis.user
    </select>
</mapper>

2.4测试Junit

package com.wangzj.dao;

import com.wangzj.pojo.User;
import com.wangzj.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

/  
 * @author wangzhijun
 * @date 2021/6/15
 * @e-mail wangzj_root@163.com
 * @describe
 */
public class UserDaoTest {
    @Test
    public void test(){
        //第一步:获得sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //第二步:
        // 方法一:get Mapper
       UserDao userDao = sqlSession.getMapper(UserDao.class);
       List<User> userList = userDao.getUserList();

        for (User user : userList) {
            System.out.println(user);
        }
       //第三步:关闭sqlsession
        sqlSession.close();
    }

}

注意:org.apache.ibatis.binding.BindingException: Type interface com.wangzj.dao.UserDao is not known to the MapperRegistry.

核心配置文件中注册Mapper(要加Mapper标签)

可能遇到的问题

  • 配置文件没有注册:

    • 注意:org.apache.ibatis.binding.BindingException: Type interface com.wangzj.dao.UserDao is not known to the MapperRegistry.

      核心配置文件中注册Mapper(要加Mapper标签)

  • 绑定接口错误

  • 方法名不对

    • 核对方法名
  • 返回类型不对

    • 核对类型
  • 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>true</filtering>
            </resource>
        </resources>
    </build>
    

在这里插入图片描述

3、CRUD(增删改查)

3.1namespace

namespace中的包名和Dao/Mapper接口的包名一致

3.2Select

选择、查询语句

  • id:就是对应的namespace中的方法名
  • resultType:SQL语句执行的返回值
  • parametertype:参数类型

1、编写接口

User getUserById(int id);

2、编写对应的Mapper中SQL语句

<select id="getUserById" parameterType="int" resultType="com.wangzj.pojo.User">    select *from mybatis.user where id = #{id} </select>

3、测试

 @Test
    public void getUserList(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.getUserById(1);
        System.out.println(user);


        sqlSession.close();
    }

注意点:增删改操作需要提交事务

3.3 Insert

 <insert id="insertUser" parameterType="com.wangzj.pojo.User">
        insert into  mybatis.user (id,name,psw)values (#{id},#{name},#{psw});
    </insert>

3.4 Update

<update id="updateUser" parameterType="com.wangzj.pojo.User">
        update mybatis.user set name=#{name},psw=#{psw} where id=#{id}
    </update>

3.5 Delete

 <delete id="deleteUser" parameterType="com.wangzj.pojo.User" >
        delete from mybatis.user where id=#{id}
    </delete>

3.6 错误排查

  • 标签不要匹配错误
  • resource绑定Mapper,需要使用路径(要用“/”)
  • 程序配置文件必须符合规范
  • NullPointerException,没有注册到资源
  • 输出的xml文件中出现乱码
  • maven没有导出问题

3.7 万能MAP

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

//    用Map增加用户信息
    Boolean insterUser2(Map<String,Object>map);
 <insert id="insterUser2" parameterType="map">
    insert into mybatis.user(id, psw)values (#{userId},#{pasword});
 </insert>
@Test
    public void insterUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("userId",5);
        map.put("pssword","11111");
        sqlSession.commit();
        sqlSession.close();

    }

Map传递参数,直接在SQL中取出key即可【 parameterType=“map”】

对象传递参数,直接在SQL中取出对象的属性即可【 parameterType=“com.wangzj.pojo.User”】

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

多个参数用Map或者注解

3.8 模糊查询

1、模糊查询怎么写?

1)java代码执行的时候,传递通配符 %%

List<User> listUser = mapper.getUserLike("%李%")

2)在SQL拼接中使用通配符

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

4、配置解析

4.1 核心配置文件

  • mybatis-config.xml

  • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。

       configuration(配置)
        properties(属性)
        settings(设置)
        typeAliases(类型别名)
        typeHandlers(类型处理器)
        objectFactory(对象工厂)
        plugins(插件)
          environments(环境配置)  
            environment(环境变量)  
           transactionManager(事务管理器)  
           dataSource(数据源)  
        databaseIdProvider(数据库厂商标识)
        mappers(映射器)
    
4.1.1 environments(环境配置)
  • MyBatis 可以配置成适应多种环境

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

    学会使用配置多套运行环境

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

4.1.2 properties(属性)

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

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

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=wzj123
  1. 在核心配置文件中引入

在这里插入图片描述

  • 可以直接映入外部文件
  • 可以在其中增加一些属性配置
  • 如果两个文件有同一个字段,优先使用外部配置文件
4.1.3 typeAliases(类型别名)
  • 类型别名可为 Java 类型设置一个缩写名字。

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

     <typeAliases>
        <typeAlias type="com.wangzj.pojo.User" alias="User"/>
     </typeAliases>
    
  • 也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean

    扫描实体类的包,它默认的别名是这个实体类的类名

    <typeAliases>
        <package name="com.wangzj.pojo"/>
    </typeAliases>
    

    一般情况下,实体类比较少的话用第一种,要是比较多就用第二种

    但是第一种可以DIY,第二种是固定的(但可以通过注解来起别名)

    @Alias("author")
    public class Author {
        ...
    }
    
4.1.4 settings(设置)

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

设置名描述有效值默认值
cacheEnabled全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。true | falsetrue
lazyLoadingEnabled延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。true | falsefalse
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING
4.1.5 其他配置
  • typeHandlers(类型处理器)

  • objectFactory(对象工厂)

  • plugins(插件)

    • MyBatis Generator Core
    • MyBatis Plus
    • 通用Mapper
4.1.6 映射器(mappers)

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

方式一:

<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

方式二:使用class文件绑定注册

<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mapper class="org.mybatis.builder.BlogMapper"/>
  <mapper class="org.mybatis.builder.PostMapper"/>
</mappers>

注意点:

  • 接口和它的Mapper配置文件必须同名
  • 接口和它的Mapper配置文件必须在同一包下

方式三:使用包扫描进行注入绑定

<!-- 将包内的映射器接口实现全部注册为映射器 --><mappers>  <package name="org.mybatis.builder"/></mappers>

注意点:

  • 接口和它的Mapper配置文件必须同名
  • 接口和它的Mapper配置文件必须在同一包下

练习:

  • 将数据库配置文件外部引入
  • 实体类别名
  • 保证UserMapper接口和UserMapper.xml改为一致,并且在同一包下

在这里插入图片描述

SqlSessionFactoryBuilder
  • 一旦创建SqlSessionFactoryBuilder,就不在需要它了
  • 局部变量
SqlSessionFactory
  • 说白了可以想象为:数据库连接池
  • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
  • 因此,SqlSessionFactory 的最佳作用域是应用作用域
  • 最简单的就是使用单例模式或者静态单例模式
SqlSession
  • 连接到连接池的一个请求
  • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
  • 用完之后必须赶紧关闭,否则资源被占用

图中的每一个Mapper,就代表一个具体的业务

5、别名

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

数据库中的字段

在这里插入图片描述

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

public class User {
    private int id;
    private String name;
    private String password;

5.1测试出现问题

在这里插入图片描述

解决方法:

  • 起别名
 <select id="getUserById" parameterType="int" resultType="User">   select name,id,psd as password from mybais.user where id=#{id} </select>

resultMap

结果集映射

    <resultMap id="UserMap" type="User"><!-- column数据库中的字段 property实体类中的属性 -->        <result column="id" property="id"/>        <result column="name" property="name"/>        <result column="psw" property="password"/>    </resultMap><!--根据ID查询对应信息-->    <select id="getUserById" parameterType="int" resultMap="UserMap">        select *from mybatis.user where id = #{id}    </select>
  • resultMap 元素是 MyBatis 中最重要最强大的元素
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了
  • ResultMap 的优秀之处,虽然你对他相当了解,你完全可以不用显式地配置它们
  • 如果这个世界总是这么简单就好了

6 日志

6.1 日志工厂

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

曾今:sout、debug

现在:日志工厂

设置名描述有效值默认值
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING未设置
  • SLF4J
  • LOG4J【掌握】
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING 【掌握】
  • NO_LOGGING

在mybatis中具体使用哪一个日志实现,在设置中设定

STDOUT_LOGGING标准日志输出

在mybatis的核心配置文件中,配置我们的日志

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-trjgUtj1-1628149386010)(E:\blog\img\微信截图_20210702113109.png)]

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

6.2 Log4j

什么是Log4j?

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

1、先导入Log4j的包

<dependencies>        <!-- https://mvnrepository.com/artifact/log4j/log4j -->        <dependency>            <groupId>log4j</groupId>            <artifactId>log4j</artifactId>            <version>1.2.17</version>        </dependency>    </dependencies>

2、 log4j.properties

由于mybatis-3.2.X没有设置控制台打印sql 的属性配置,因此此处采用,打印日志方式将sql打印
在控制台
在编码测试过程,日志级别为debug ;
如果是项目上线,日志级别改为info

log4j.rootLogger=DEBUG,CONSOLE,file
#log4j.rootLogger=ERROR,ROLLING_FILE
log4j.logger.com.mapper=debug
log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=debug
log4j.logger.org.tuckey.web.filters.urlrewrite.UrlRewriteFilter=debug
################################################################################
######
# Console Appender \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e
################################################################################
######
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=error
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n
################################################################################
######
# DailyRolling File
\u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff0c\u6587\u4ef6\
u540d\u683c\u5f0f:log2009-09-11
################################################################################
######
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern=yyyy-MM-dd
log4j.appender.file.File=log.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=error
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L)
%m%n
log4j.logger.com.opensymphony.xwork2=error

3、配置log4j为日志的实现

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

4、log4j的使用,直接测试运行刚才的查询

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sQ0iEvyx-1628149386011)(E:\blog\img\微信截图_20210702160256.png)]

6.3简单使用

1、在要使用log4j的类中,导入包org.apache.log4j.Logger;

2、日志对象,参数为当前类的class

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

3、日志级别

  logger.info("info:进入了testLog4j");//信息 相当于System.out.println(); 但他是有级别的        logger.debug("debug:进入了testLog4j");        logger.error("error:进入了testLog4j");

7 分页

思考:为什么要分页?

  • 减少数据的处理量
7.1 使用limit分页
select * from user limit 3;#[0,n] n=3
select * from user limit 1,2;

使用mysql实现分页,核心SQL

  • 接口
  List<User> getUserByLimit(Map<String,Integer> map );
  • Mapper.xml
  <!--    limit分页-->      <select id="getUserByLimit" parameterType="map" resultMap="UserMap">          select *from mybatis.user Limit #{startIndex},#{pageSize};      </select>
  • 测试
   @Test      public void getUserByLimit(){          SqlSession sqlSession = MybatisUtils.getSqlSession();          UserMapper mapper = sqlSession.getMapper(UserMapper.class);          HashMap<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(map);          }          sqlSession.close();      }

7.2 RowBounds分页

不再使用SQL分页实现分页

  • 接口

    //    使用RowBounds分页
    List<User> getUserByRowBounds();
    
  • Mapper.xml

    <!--    RowBounds分页-->
    <select id="getUserByRowBounds" resultMap="UserMap">
      select *from mybatis.user
    
  • 测试

    @Test
    public void getUserByRowBounds(){
      SqlSession sqlSession = MybatisUtils.getSqlSession();
      //        通过RowBounds实现
      RowBounds rowBounds = new RowBounds(1,2);
      //        通过java层面实现分页
      List<User> userList = sqlSession.selectList("com.wangzj.dao.UserMapper.getUserByRowBounds",null,rowBounds);
      for (User  user : userList) {
        System.out.println(user);
      }
      sqlSession.close();
    }
    

    7.3使用mybatis-pagehelper插件实现分页【了解】

在这里插入图片描述

网址:https://pagehelper.github.io/

8、使用注解开发

8.1面向接口编程

​ 在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。

使用面向接口编程的根本原因:

  • 1 降低程序的耦合性。其能够最大限度的解耦,所谓解耦既是解耦合的意思,它和耦合相对。耦合就是联系 ,耦合越强,联系越紧密。在程序中紧密的联系并不是一件好的事情,因为两种事物之间联系越紧密,你更换 其中之一的难度就越大,扩展功能和debug的难度也就越大。
  • 2 易于程序的扩展;
  • 3 有利于程序的维护
8.1.1.关于接口的理解。

接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。

接口的本身反映了系统设计人员对系统的抽象理解。

接口应有两类:第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);

第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface);

一个体有可能有多个抽象面。

抽象体与抽象面是有区别的。

8.1.2三个面向的区别
  1. 面向对象:我们考虑问题时,以对象为单位,要考虑实例化对象的属性和方法
  2. 面向过程:当考虑问题时,是以一个具体流程(事务过程)为单位,考虑它的实现
  3. 面向接口:本质上与面对过程和面对对象不是一个问题,更多的是考虑它整体的一个架构

8.2 使用注解开发:happy:

  1. 注解在接口上实现
 @Select("select *from mybatis.user")List<User> getUsers();
  1. 需要在核心配置文件中绑定接口
   <!--    绑定接口-->       <mappers>           <mapper class="com.wangzj.dao.UserMapper"/>       </mappers>
  1. 测试

      @Test    public void test(){        SqlSession sqlSession = MybatisUtils.getSqlSession();//        底层主要用反射来实现        UserMapper mapper = sqlSession.getMapper(UserMapper.class);        List<User> users = mapper.getUsers();        for (User user : users) {            System.out.println(user);        }        sqlSession.close();    }
    

本质:反射机制实现

底层:动态代理
在这里插入图片描述

8.1.3 mybatis详细的执行流程

在这里插入图片描述

8.2 注解实现CRUD

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

//    既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。//    SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。 public static SqlSession getSqlSession(){        return sqlSessionFactory.openSession(true);    }
接口
public interface UserMapper {    @Select("select *from mybatis.user")    List<User> getUsers();//    方法存在多个参数,所有的参数前面加上@Param    @Select("select *from mybatis.user where id=#{id} and name=#{name}")    User getUserById(@Param("id") int id,@Param("name")String name);//   用注解删除一个用户    @Delete("delete from mybatis.user where id=#{id}")    int deteleUser(@Param("id") int id);//    增加一个用户    @Insert("insert into mybatis.user (id,name,psw) values(#{id},#{name},#{password})")    int addUser(User user);//    修改用户信息    @Update("update mybatis.user set name=#{name},psw=#{password} where id=#{id}")    int updateUser(User user); }
测试

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

<--绑定接口--><mappers>   <mapper class="com.wangzj.dao.UserMapper"/></mappers>
   @Test    public void test1(){//        底层主要用反射来实现        UserMapper mapper = sqlSession.getMapper(UserMapper.class);        List<User> users = mapper.getUsers();        User root = mapper.getUserById(1, "root");        System.out.println(root);        sqlSession.close();    }    @Test    public void deleteUser(){        UserMapper mapper = sqlSession.getMapper(UserMapper.class);        mapper.deteleUser(5);        sqlSession.close();    }    @Test    public void addUser(){        UserMapper mapper = sqlSession.getMapper(UserMapper.class);        mapper.addUser(new User(5,"wangr","687"));        sqlSession.close();    }    @Test    public void updateUser(){        SqlSession sqlSession = MybatisUtils.getSqlSession();        UserMapper mapper = sqlSession.getMapper(UserMapper.class);        mapper.updateUser(new User(5,"wangzj","342432"));        sqlSession.close();    }}
关于@Param()注解
  • 基本类型的参数或Spring类型要加
  • 引用类型不需要加
  • 如果只有一个基本类型是 可忽略【建议加上】
  • 我们在SQL中引用的就是我们这里设定的属性名@Param(“id”)
#{}和${}的区别
  • #{} : 采用预编译方式,可以防止SQL注入
  • ${}: 采用直接赋值方式,无法阻止SQL注入攻击

9、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.

Features@Getter and @Setter@FieldNameConstants@ToString@EqualsAndHashCode@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog@Data@Builder@SuperBuilder@Singular@Delegate@Value@Accessors@Wither@With@SneakyThrows@val@varexperimental @var@UtilityClassLombok config systemCode inspectionsRefactoring actions (lombok and delombok)

@Data:无参构造、get、set、String、Equals、hsshcode

使用步骤:
  1. 在IDEA中安装Lombok插件

  2. 在项目中导入Lombok的jar包

     <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->        <dependency>            <groupId>org.projectlombok</groupId>            <artifactId>lombok</artifactId>            <version>1.18.12</version>        </dependency>
    
  3. 在实体类加注解即可

    @Data@AllA rgsConstructor@NoArgsConstructorpublic class User {    private int id;    private String name;    private String password;   }
    

10、多对一处理

在这里插入图片描述

10.1多对一

  • 多个学生对应一个老师

  • 对于学生而言,多个学生关联一个老师【多对一】

  • 对于老师而言,集合,一个老师有很多学生【一对多】

在这里插入图片描述

-- DROP TABLE IF EXISTS `student`;CREATE TABLE `student` (  `sid` INT(11) DEFAULT NULL,  `tid` INT(11) DEFAULT NULL,  `sname` VARCHAR(20) DEFAULT NULL,  `sage` INT(11) DEFAULT NULL,  `ssex` VARCHAR(20) DEFAULT NULL) ENGINE=INNODB DEFAULT CHARSET=utf8;-- ------------------------------ Records of student-- ----------------------------INSERT INTO `student` VALUES ('1', '1', '刘一', '18', '男');INSERT INTO `student` VALUES ('2', '2', '钱二', '19', '女');INSERT INTO `student` VALUES ('3', '3', '张三', '17', '男');INSERT INTO `student` VALUES ('4', '4', '李四', '18', '女');INSERT INTO `student` VALUES ('5', '1', '王五', '17', '男');INSERT INTO `student` VALUES ('6', '4', '赵六', '19', '女');-- DROP TABLE IF EXISTS `teacher`;CREATE TABLE `teacher` (  `tid` INT(11) DEFAULT NULL,  `sid` INT(11) DEFAULT NULL,  `tname` VARCHAR(20) DEFAULT NULL) ENGINE=INNODB DEFAULT CHARSET=utf8;-- ------------------------------ Records of teacher-- ----------------------------INSERT INTO `teacher` VALUES ('1', '1', '叶平');INSERT INTO `teacher` VALUES ('2', '2', '贺高');INSERT INTO `teacher` VALUES ('3', '3', '杨艳');INSERT INTO `teacher` VALUES ('4', '4', '周磊');-- DROP TABLE IF EXISTS `course`;CREATE TABLE `course` (  `cid` INT(11) DEFAULT NULL,  `cname` VARCHAR(255) DEFAULT NULL,  `tid` INT(11) DEFAULT NULL) ENGINE=INNODB DEFAULT CHARSET=utf8;-- ------------------------------ Records of course-- ----------------------------INSERT INTO `course` VALUES ('1', '语文', '1');INSERT INTO `course` VALUES ('2', '数学', '2');INSERT INTO `course` VALUES ('3', '英语', '3');INSERT INTO `course` VALUES ('4', '物理', '4');-- DROP TABLE IF EXISTS `sc`;CREATE TABLE `sc` (  `sid` INT(11) DEFAULT NULL,  `cid` INT(20) DEFAULT NULL,  `score` INT(11) DEFAULT NULL) ENGINE=INNODB DEFAULT CHARSET=utf8;-- ------------------------------ Records of sc-- ----------------------------INSERT INTO `sc` VALUES ('1', '1', '60');INSERT INTO `sc` VALUES ('1', '2', '78');INSERT INTO `sc` VALUES ('1', '3', '67');INSERT INTO `sc` VALUES ('1', '4', '58');INSERT INTO `sc` VALUES ('2', '1', '79');INSERT INTO `sc` VALUES ('2', '2', '81');INSERT INTO `sc` VALUES ('2', '3', '92');INSERT INTO `sc` VALUES ('2', '4', '68');INSERT INTO `sc` VALUES ('3', '1', '91');INSERT INTO `sc` VALUES ('3', '2', '47');INSERT INTO `sc` VALUES ('3', '3', '88');INSERT INTO `sc` VALUES ('3', '4', '56');INSERT INTO `sc` VALUES ('4', '2', '88');INSERT INTO `sc` VALUES ('4', '3', '90');INSERT INTO `sc` VALUES ('4', '4', '93');INSERT INTO `sc` VALUES ('5', '1', '46');INSERT INTO `sc` VALUES ('5', '3', '78');INSERT INTO `sc` VALUES ('5', '4', '53');INSERT INTO `sc` VALUES ('6', '1', '35');INSERT INTO `sc` VALUES ('6', '2', '68');INSERT INTO `sc` VALUES ('6', '4', '71');
10.1.1 测试环境搭建
  1. 导入Lombok
  2. 新建实体类Teacher、Student、Score、Course
  3. 建立Mapper接口
  4. 建立Mapper.xml
  5. 在核心配置文件中绑定注册我们的Mapper接口或者文件
  6. 测试查询是否能够成功
10.1.2 出现问题,解决问题
  • 出现问题

接口

// 当我们想查询学生信息和老师的信息时public List<Student> getStudent();

配置

<select id="getStudent" resultType="Student">    select *from student;</select>

测试

public class StudentTest {    static  SqlSession sqlSession = MybatisUtils.getSqlSession();    @Test    public void getStudent(){        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);        List<Student> studentList = mapper.getStudent();        for (Student student : studentList) {            System.out.println(student);        }        sqlSession.close();    }}

运行结果:

在这里插入图片描述

解决问题

方法一:按照查询嵌套处理(相当于一个子查询)

思路:

​ 1、查询所有的学生信息

​ 2、根据查询出来的学生ID,寻找对应的老师

<select id="getStudent" resultType="Student">    select *from student;</select><select id="getTeacher" resultType="Teacher">   select *from teacher where tid=#{tid};</select>

这是最初的思路,就是先将学生的所有信息查出来,再根据id找出老师的所有信息 那么我们将如何把这两个连起来呢?

  1. 首先我们将resultType="Student"改成resultMap=“StudentTeacher”;因为resultMap是为了结果集映射

  2. 接着我们来写resultMap,前三个result应该都能理解,但是第四个就是注释所说的;因为在我们的实体类中teacher的类型是对象,属于是复杂类型,所以我们要用association来处理。

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gAwxZN4D-1628149386015)(E:\blog\img\image-20210714171149854.png)]

    <resultMap id="StudentTeacher" type="Student">            <result property="sid" column="sid"/>            <result property="sage" column="sage"/>            <result property="ssex" column="ssex"/>         <!--当遇到复杂的属性时,我们需要单独处理:          当一个属性为一个对象时我们用association;         当属性为一个集合时我们采用collection		<collection property="" column=""/>		-->            <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/> </resultMap>
    

    3.在的属性中多出来了两个,其中javaType是说明类型的,在实体类中我们可以看到teacher是Teacher类型,而另外一个select就是链接两个查询的关键,getTeacher就是下一个查询的ID。下面就是所有代码

    接口

    //    查询所有的学生信息以及老师的所有信息
            public List<Student> getStudent();
    

    配置

     <select id="getStudent" resultMap="StudentTeacher">
                select *from student;
            </select>
    
            <resultMap id="StudentTeacher" type="Student">
                <result property="sid" column="sid"/>
                <result property="sage" column="sage"/>
                <result property="ssex" column="ssex"/>
             <!--当遇到复杂的属性时,我们需要单独处理:
              当一个属性为一个对象时我们用association;
             当属性为一个集合时我们采用collection-->
                <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    <!--            <collection property="" column=""/>-->
            </resultMap>
    
            <select id="getTeacher" resultType="Teacher">
                select *from teacher where tid=#{tid};
            </select>
    

    测试

     @Test    public void getStudentTest(){        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);        List<Teacher> teacherList = mapper.getTeacher();        for (Teacher teacher : teacherList) {            System.out.println(teacher);        }        sqlSession.close();    }
    
方法二 按照结果嵌套处理(相当于是联表查询)

不多说,直接上代码;接口就不写了,更上面的一样;唯一注意的就是association里边写的就是另外一个表的字段

配置文件

		<select id="getStudent1" resultMap="StudentTeacher1">             select *from student,teacher             where student.tid=teacher.tid;        </select>        <resultMap id="StudentTeacher1" type="Student">            <result property="sid" column="sid"/>            <result property="sage" column="sage"/>            <result property="ssex" column="ssex"/>            <association property="teacher" javaType="Teacher">                <result property="sid" column="sid"/>                <result property="tid" column="tid"/>                <result property="tname" column="tname"/>            </association>        </resultMap>

测试

@Test
    public void getStudentTest1(){

        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studentList = mapper.getStudent1();
        for (Student student : studentList) {
            System.out.println(student);
        }
        sqlSession.close();
    }

多对一就两种方式

  • 子查询
  • 联表查询

11、一对多处理

比如:一个老师拥有多个学生

对于老师来说就是一对多的关系

11.1 环境搭建

方法一:按照结果嵌套处理(相当于是联表查询)

1、搭建环境其实就和上面的一样

实体类

@Datapublic class Student {    private int sid;    private String name;    private int sage;    private String ssex;    private int tid;}
@Datapublic class Teacher {    private int tid;    private String tname;    private List<Student> students;}

Mapper接口

public interface TeacherMapper {//    查询老师和学生的所有信息‘    List<Teacher> getTeacher(@Param("tid") int tid);}

Mapper.xml配置文件

​ 上面的都跟多对一的差不多,这里就不细说了;Mapper.xml中就有点不一样了;在resultMap中,由于一对多中Student是一个集合,所以我们需要使用而不是了,还有一点就是中的ofType属性,因为它是一个集合类型的,所以我在其中要使用ofType。JavaType是指定属性的类型而集合中的泛型信息我们使用ofType。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
        <mapper namespace="com.wangzj.dao.TeacherMapper">
            <select id="getTeacher" resultMap="TeacherStudent">
                select  *from mybatis.teacher,mybatis.student
                where student.tid=teacher.tid
                and teacher.tid=#{tid}
            </select>
        <resultMap id="TeacherStudent" type="Teacher">
            <result property="tid" column="tid"/>

            <result property="tname" column="tname"/>
            <collection property="students" ofType="Student">
                <result property="tid" column="tid"/>
                <result property="sid" column="sid"/>
                <result property="ssex" column="ssex"/>
                <result property="sname" column="sname"/>
                <result property="sage" column="sage"/>
            </collection>
        </resultMap>
        </mapper>

测试类

public class TeacherTest {    static  SqlSession sqlSession = MybatisUtils.getSqlSession();@Test    public void testTeacher(){    TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);    List<Teacher> teacherList = mapper.getTeacher(1);    for (Teacher teacher : teacherList) {        System.out.println(teacher);    }    sqlSession.close();}}

方式二:按照查询嵌套处理(相当于一个子查询)

按照查询嵌套处理这种方式比较复杂,个人推崇第一种。

Mapper.xml配置文件

 <select id="getTeacher2" resultMap="teacherStu2">
        select * from teacher where id = #{id}
    </select>
    <resultMap id="teacherStu2" type="com.me.domain.Teacher2" >
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <collection property="students" javaType="ArrayList" ofType="com.me.domain.Student2" 				select="getStudentByTid" column="id"/>
    </resultMap>


    <select id="getStudentByTid" resultType="com.me.domain.Student2">
        select * from student where tid = #{id}
    </select>

测试类

@Test   
public void getTeacher2(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher2 teacher = mapper.getTeacher2(1);
        System.out.println(teacher.toString());
        sqlSession.close();
    }

小结

1、关联-association【多对一】

2、集合-collection【一对多】

3、JavaType&JavaType?

​ JavaType是指定实体类中属性的类型;ofType说白了就是泛型中的约束类型

注意点:

​ 1、保证SQL的可读性,尽量保证通俗易懂

​ 2、注意一对多和多对一中,属性名和字段名名的问题

​ 3、如果错误不好排查可以使用日志,个人推崇Log4j

高频!!!高频!!! 高频!!!

  • mysql引擎
  • InnoDB底层原理
  • 索引
  • 索引优化

12、动态SQL

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

利用动态 SQL,可以彻底摆脱这种痛苦。

如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。ifchoose (when, otherwise)trim (where, set)foreach

12.1 搭建环境

-- DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `sid` INT(11) DEFAULT NULL,
  `tid` INT(11) DEFAULT NULL,
  `sname` VARCHAR(20) DEFAULT NULL,
  `sage` INT(11) DEFAULT NULL,
  `ssex` VARCHAR(20) DEFAULT NULL
) ENGINE=INNODB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('1', '1', '刘一', '18', '男');
INSERT INTO `student` VALUES ('2', '2', '钱二', '19', '女');
INSERT INTO `student` VALUES ('3', '3', '张三', '17', '男');
INSERT INTO `student` VALUES ('4', '4', '李四', '18', '女');
INSERT INTO `student` VALUES ('5', '1', '王五', '17', '男');
INSERT INTO `student` VALUES ('6', '4', '赵六', '19', '女');
创建一个基础工程
  1. 导包(pom.xml)

  2. 编写配置文件(resources)

  3. 编写实体类

    @Data
    public class Student {
        private int sid;
        private String sname;
        private int sage;
        private String ssex;
        
    }
    
  4. 编写实体类对应的Mapper接口和Mapper.xml文件

12.2 IF

Mapper接口

public interface StudentsMapper {//    添加内容    int addStudents(Students students);    List<Students> getStudentsIf(Map map);}

Mapper.xml文件

<select id="getStudentsIf" parameterType="Students" resultType="map">  select *from mybatis.students where 1=1  <if test="Sname!=null">    Sname=#{Sname}  </if>  <if test="Ssex!=null">    and Ssex=#{Ssex}  </if></select>

Test

@Testpublic void getStudentsIfTest9(){  StudentsMapper mapper = sqlSession.getMapper(StudentsMapper.class);  HashMap map = new HashMap();  map.put("Ssex","男");  mapper.getStudentsIf(map);  sqlSession.close();}

12.3 where&choose&when

Mapper接口

public interface StudentsMapper {
  
    List<Students> getStudentsChoose(Map map);
}

Mapper.xml文件

<select id="getStudentsChoose" parameterType="map" resultType="Students">
  select *from mybatis.students
  <where>
    <choose>
      <when test="Sname!=null">
        and Sname=#{Sname}
      </when>

      <otherwise>
        and Ssex=#{Ssex}
      </otherwise>
    </choose>
  </where>
</select>

Test

@Testpublic void getStudentsChooseTeat(){  StudentsMapper mapper = sqlSession.getMapper(StudentsMapper.class);  HashMap map = new HashMap();  //        map.put("Sname","王芝军");  //        map.put("Ssex","男");  List<Students> studentsChoose = mapper.getStudentsChoose(map);  for (Students students : studentsChoose) {    System.out.println(students);  }  sqlSession.close();}

12.4 sql片段

Mapper接口

public interface StudentsMapper {     List<Students> getStudentsIf(Map map);}

Mapper.xml文件

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

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

<sql id="if_name_sex">  <if test="Sname!=null">    and Sname=#{Sname}  </if>  <if test="Ssex!=null">    and Ssex=#{Ssex}  </if></sql>

2、在需要使用的地方使用include标签引用即可

<select id="getStudentsIf" parameterType="map" resultType="Students">  select *from mybatis.students  <where>    <include refid="if_name_sex"></include>  </where></select>

Test

@Test
public void getStudentsIfTest9(){
  StudentsMapper mapper = sqlSession.getMapper(StudentsMapper.class);
  HashMap map = new HashMap();
  map.put("Ssex","男");
  mapper.getStudentsIf(map);
  sqlSession.close();
}

3、注意事项:

​ 最好基于单标来定义SQl片段

​ 不要存在where标签

12.5 Foreach

Mapper接口

public interface StudentsMapper {    List<Students> getStudentsForech(Map map);}

Mapper.xml文件

<select id="getStudentsForech" parameterType="map" resultType="Students">  select *from mybatis.students  <where>    <foreach collection="ids" item="Sid" open="(" close=")" separator="or">      Sid=#{Sid}    </foreach>  </where></select>

Test

@Testpublic void getStudentsForech(){  StudentsMapper mapper = sqlSession.getMapper(StudentsMapper.class);  HashMap map = new HashMap();  ArrayList<Integer> ids = new ArrayList<Integer>();  ids.add(1);  ids.add(2);  ids.add(3);  ids.add(4);  map.put("ids",ids);  List<Students> studentsForech = mapper.getStudentsForech(map);  for (Students idss : studentsForech) {    System.out.println(idss);  }  sqlSession.close();}

12.6 trim自定义

13、缓存

13.1 cache 简介

13.1.1 什么是缓存(Cache)?

在这里插入图片描述

☞ 缓存就是数据交换的缓冲区,当某一硬件要读取数据时,会首先从缓存汇总查询数据,有则直接执行,不存在时从内存中获取。由于缓存的数据比内存快的多,所以缓存的作用就是帮助硬件更快的运行

13.1.2 为什么要使用缓存?

☞ 高性能
假如有1000个请求要去查询同一条数据,如果1000个请求直接去数据库中查找,而且这个查找sql比较耗时,那么这1000个请求每个都会很慢.
如果在查询系统和数据库中间加一层缓存,那么第一个请求查询数据库,会慢一点,查出来结果保存到缓存中,只要这个数据在一段时间内不会改变,其他999个请求就可以都去缓存中查询数据,就会很快
如果数据在后续变化了,系统在修改数据库的同时,去更新一下缓存中的数据就可以了
☞ 高并发
在高并发的时候,瞬间每秒压力激增,数据库承受不住一下子涌入的请求,可以把很多数据放在缓存中,从缓存中去操作,大幅度提升性能一般公司都是用缓存来实现高性能的

13.1.3 什么样的数据应该放入缓存

把数据放入缓存,有三个标准:

1.数据量不大

2.访问频率高

3.数据更改频率低

13.2 Mybatis缓存

  • Mybatis包含一个非常强大的查询缓存特性,它可以非常方便的定制和配置缓存。缓存可以极大地提升查询效率。

  • Mybatis系统中默认定义了两级缓存:一级缓存和二级缓存

    ☞ 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称作本地缓存)

    ☞ 二级缓存需要手动开启和配置,它基于namespace级别的缓存

    ☞ 为了提高扩展性,Mybatis定义了缓存窗口Cache。我们可以通过Cache接口来自定义二级缓存

13.3 Mybatis一级缓存

Mybatis对缓存提供支持,但是在没有配置的默认情况下,它只开启一级缓存,一级缓存只是相对于同一个SqlSession而言。所以在参数和SQL完全一样的情况下,我们使用同一个SqlSession对象调用一个Mapper方法,往往只执行一次SQL,因为使用SelSession第一次查询后,MyBatis会将其放在缓存中,以后再查询的时候,如果没有声明需要刷新,并且缓存没有超时的情况下,SqlSession都会取出当前缓存的数据,而不会再次发送SQL到数据库

在这里插入图片描述

测试步骤:

1、开启日志

2、测试在一个Session中查询两次相同的记录和查询两次不相同的记录
在这里插入图片描述

在这里插入图片描述

3、查看日志输出

缓存失效的情况:

​ ☞ 增删改操作可能会改变原来的数据,所以必定会刷新缓存

在这里插入图片描述

​ ☞ 查询不同的数据

​ ☞ 查询不同的Mapper.xml

​ ☞ 手动清理缓存

在这里插入图片描述

小结:一级缓存默认是开起的,只在一次Sqlsession中有效 ,也就是拿到链接到关闭连接之间有效

所有代码:

Mapper

public interface UserMapper {
    List<User> getAllUser();
    User getUser(@Param("id")int id);
    int updateUser(User user);
}

Mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wangzj.dao.UserMapper">
    <select id="getAllUser" parameterType="map" resultType="User">
        select *from mybatis.user
    </select>
    <select id="getUser"  resultType="User">
        select *from mybatis.user where id=#{id}
    </select>
    <update id="updateUser" parameterType="User">
        UPDATE mybatis.user set name=#{name},psw=#{psw} where id=#{id}
    </update>
</mapper>

测试

@Testpublic void getUser(){  SqlSession sqlSession = MybatisUtils.getSqlSession();  UserMapper mapper = sqlSession.getMapper(UserMapper.class);  User user = mapper.getUser(1);  System.out.println(user);  //        手动清理缓存  sqlSession.clearCache();  //        mapper.updateUser(new User(2,"aaaaaaaaaa","bbbbbbbbb"));  System.out.println("====================================");  User user1 = mapper.getUser(1);  User user2 = mapper.getUser(2);  System.out.println(user);  sqlSession.close();}

13.4 Mybatis二级缓存

MyBatis的二级缓存是Application级别的缓存,它可以提高对数据库查询的效率,以提高应用的性能。

在这里插入图片描述

如上图所示,当开一个会话时,一个SqlSession对象会使用一个Executor对象来完成会话操作,MyBatis的二级缓存机制的关键就是对这个Executor对象做文章。如果用户配置了"cacheEnabled=true",那么MyBatis在为SqlSession对象创建Executor对象时,会对Executor对象加上一个装饰者:CachingExecutor,这时SqlSession使用CachingExecutor对象来完成操作请求。CachingExecutor对于查询请求,会先判断该查询请求在Application级别的二级缓存中是否有缓存结果,如果有查询结果,则直接返回缓存结果;如果缓存中没有,再交给真正的Executor对象来完成查询操作,之后CachingExecutor会将真正Executor返回的查询结果放置到缓存中,然后在返回给用户。

实现Mybatis二级缓存步骤:

  1. 开启全局缓存
<!--显式的开启全局缓存--><setting name="cacheEnabled" value="true"/>
  1. 在要使用二级缓存的Mapper中开启
<!--在当前Mapper.xml中开启二级缓存--><cache/>

也可以自定义参数

<!--在当前Mapper.xml中开启二级缓存--><cache       eviction="FIFO"       flushInterval="60000"       size="512"       readOnly="true"/><!--这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。-->

测试

@Test
public void secondCache(){
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  SqlSession sqlSession1 = MybatisUtils.getSqlSession();

  UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  User user = mapper.getUser(1);
  System.out.println(user);
  sqlSession.close();
  //        手动清理缓存
  //        sqlSession.clearCache();
  //        mapper.updateUser(new User(2,"aaaaaaaaaa","bbbbbbbbb"));

  System.out.println("====================================");

  UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
  User user1 = mapper1.getUser(1);
  System.out.println(user);

  //        User user1 = mapper.getUser(1);
  //        User user2 = mapper.getUser(2);
  //        System.out.println(user);

  sqlSession1.close();
}

在这里插入图片描述

出现的问题:

  1. 我们需要将实体类序列化,否则就会报错
org.apache.ibatis.cache.CacheException: Error serializing object.  Cause: java.io.NotSerializableException: com.wangzj.pojo.User
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    private int id;
    private String name;
    private String psw;
}

可用的清除策略(eviction)有:

  • LRU – 最近最少使用:移除最长时间不被使用的对象。
  • FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
  • SOFT – 软引用:基于垃圾回收器状态和软引用规则移除对象。
  • WEAK – 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。

在这里插入图片描述

缓存顺序:

  1. 首先要看二级缓存中有没有
  2. 再看一级缓存中有没有
  3. 最后再从数据库查询

总结:

1.Mybatis 一级缓存/二级缓存命中原则
  1. sql id
  2. 查询参数
  3. 分页参数
  4. sql语句
  5. 环境
    一级缓存前期:SqlSession内
    二级缓存前提:SqlSessionactory内
2.Mybatis 一级缓存生命周期

产生:调用查询语句时
销毁:Session关闭,Conmit提交,Rolback回滚,Update,ClearCahche

3.Mybatis 二级缓存生命周期

产生:调用查询语句,并执行了sqlsession.close();
销毁:Update

13.4 EhCache

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

要在程序中使用Ehcache,要先导包

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值