MyBaties总结

文章目录


一、MyBaties介绍

在这里插入图片描述
最好的学习方式:看官网文档。

(1)什么是MyBaties?

  • MyBatis 是一款优秀的持久层框架
  • 它支持定制化 SQL、存储过程以及高级映射。
  • MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
  • MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJO映射成数据库中的记录。
  • MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software
    foundation迁移到了google code,并且改名为MyBatis

折叠

(2)maven的引入

引入依赖包:

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.11</version>
</dependency>

在这里插入图片描述
3种方式都可以。

(3)持久化和持久层

  • 数据持久化:
    • 持久化就是将程序数据在瞬时状态和持久状态转化的过程。
    • 内存:断电即失。
    • 持久化实例:数据库(jdbc),IO文件持久化。冰箱冷藏。
  • 为什么需要持久化:
    • 有些对象,不能让它丢掉。
    • 内存太贵!
  • 持久层:
    • Dao层,Service层,Controller层…
    • 持久化是一个动作,持久层是一个概念,表示完成持久化工作的代码块。 层界限非常敏感。

(4)为什么需要MyBaties?(好处)

  • 框架:自动化操作。
  • 传统的JDBCD代码太复杂了,框架可以简化这个过程。

在myBaties框架中,sql是写在配置文件里的,都不用写在java代码里。做到了sql和代码的分离。

(5)github中下载的步骤

在github中搜索mybatis:

在这里插入图片描述
第二个mybaties本身。
在这里插入图片描述

点击Releases:

在这里插入图片描述
压缩包可以直接下载,下载下来就是它的jar包。

二、第一个Mybatis程序

思路:搭建环境->导入MyBatis->编写代码->测试。
(学习一个新东西,任何东西按照这个逻辑来,不会有任何问题。)

(1)搭建环境

1.1 创建数据库和表

新建myBatis数据库,创建user表并添加数据。
在这里插入图片描述

1.2 新建项目

  • 1.创建一个普通的maven项目
  • 2.删除src目录
  • 3.导入maven依赖:
    <!--导入依赖-->
    <dependencies>
<!--        mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</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>
  • 4.在该项目下 新建一个模块(新建一个maven子项目)
    这样创建的好处是子项目不用每次都去导包了。

(2)导入Mybatis

2.1编写mybatis的核心配置文件:

在这里插入图片描述
名字为mybatis-config.xml (名字不能错):

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
<!--    Environments:多套环境,default可以选择其中一个环境作为默认的环境。-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
<!--                在xml文件中,&不能用,需要转义&amp。-->
                <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="123456"/>
            </dataSource>
        </environment>
    </environments>
    
<mappers>
<!--  注册xxxMapper.xml文件,  路径以/代替.-->
 <mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>

</configuration>

2.2编写mybatis工具类MybatisUtils :

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

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

}

(3)编写代码

1.实体类User

package com.kuang.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 + '\'' +
                '}';
    }
}

2.Dao接口:

import com.kuang.pojo.User;
import java.util.List;
public interface UserDao {
     List<User> getUserList();
}

3.接口的实现类/对应的Mapper.xml文件:
(接口实现类由原来的UserDaolmpl转变为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接口,实现原理就相当于Dao对应的Impl实现了这个接口-->
<mapper namespace="com.kuang.dao.UserDao">
    <!--    select查询语句,ID对应接口中的方法名-->
    <select id="getUserList" resultType="com.kuang.pojo.User">
        <!--sql语句写在配置文件里面。-->
        select * from mybatis.user;
    </select>

</mapper>

(4)测试

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

import java.util.List;

public class UserDaoTest {
    @Test
    public void test(){
//        第一步:获取sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();

//方式一:getMapper
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();
//方式二:
//        List<User> userList = sqlSession.selectList("com.kuang.dao.UserDao.getUserList");

        for (User user : userList) {
            System.out.println(user);
        }
        //关闭操作非常重要。
  sqlSession.close();

    }
}

方式二已经过时了。不用掌握,但是需要知道它存在。

第一种方式,通过mapper直接获取它的类,就可以调用类中的方法了。
方式二会根据方法的返回值去返回。

(5)可能出现的异常

初始化失败异常。

资源导出问题。无法找出.xml文件。

在这里插入图片描述

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

2.xxxMapper.xml配置文件没有注册:

在这里插入图片描述

<mappers>
<!--    路径以/代替.-->
 <mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>

3.常见问题:

在这里插入图片描述

(6)注意事项

1.xxxMapper.xml文件和实现类的比较:

在这里插入图片描述

  • 只需记住这两个,type表示类型,map表示集合。即前者可以返回一个,后者可以返回多个。一般都是用ResultType
  • 返回结果要用完全限定名(全类名),因为配置文件不像java类能够去找它的关联。
  • 所有的集合都只需要写集合里面泛型中的东西

在这里插入图片描述

  • 原来实现接口需要重写接口的方法,现在写一个标签指向要重写的方法就可以了。
  • 原来要执行sql还需要连接数据库等jdbc的语句,现在在xml中只用执行sql就可以了。

在这里插入图片描述

2.mybatis三个核心接口:

在这里插入图片描述
在这里插入图片描述

sqlSession的关闭操作非常重要。

三、增删改查实现

(1)namespace

xml文件在这里注册了,注册时绑定的namespace命名空间。通过这个xml文件去找实例的接口。
因此namespace中的包名要和Dao/Mapper接口中的包名一致。

在这里插入图片描述

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

在这里插入图片描述

(2)select

1.编写接口:

//     查询全部用户
     List<User> getUserList();
//根据id查询用户
     User getUserById(int id);

2.编写对应的mapper中的sql语句:

    <!--    select查询语句,ID对应接口中的方法名-->
    <select id="getUserList" resultType="com.kuang.pojo.User">
        <!--sql语句写在配置文件里面。-->
        select * from mybatis.user;
    </select>

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

3.测试:

	@Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User userById = mapper.getUserById(1);
        System.out.println(userById);
        sqlSession.close();
    }

(3)insert

1.编写接口:

//     insert 一个用户
     int addUser(User user);

2.编写对应的mapper中的sql语句:

<!--    插入一个用户-->
    <insert id="addUser" parameterType="com.kuang.pojo.User">
        insert into mybatis.`user` VALUES(#{id},#{name},#{pwd})
    </insert>

3.测试:

    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int user = mapper.addUser(new User(5, "擎天柱", "111111"));
        System.out.println(user);
        sqlSession.commit();
        sqlSession.close();
    }

(4)update

1.编写接口:

//     修改一个用户
     int updateUser(User user);

2.编写对应的mapper中的sql语句:

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

3.测试:

   @Test
    public void updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int update = mapper.updateUser(new User(4, "大黄蜂", "123456"));
        System.out.println(update);
        sqlSession.commit();
        sqlSession.close();
    }

(5)delete

1.编写接口:

//     删除一个用户
     int delUser(int id);

2.编写对应的mapper中的sql语句:

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

3.测试:

   @Test
    public void delUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int i = mapper.delUser(4);
        System.out.println(i);
        sqlSession.commit();
        sqlSession.close();
    }

(6)注意事项

  • 1.所有的操作只跟接口和配置文件有关。实体类和工具类不需要变。
  • 2.sqlSession默认开启事务,最后需要提交事务,才会将数据写入导数据库中。(增删改需要提交事务)
	sqlSession.commit();
  • 3.增删改可以不用返回值
  • 4.1.这个地方必须是包名.不是/
    在这里插入图片描述
  • 4.2.crud对应的标签不要匹配错。
    在这里插入图片描述
  • 4.3.resource资源路径,这里是/代表一个文件路径。
    在这里插入图片描述
  • 4.4.mybatis核心配置文件中的代码不要写错。
    在这里插入图片描述

比如这里多了个引号。

  • 4.5. 读错从下往上读,读最下面的这个错。
    在这里插入图片描述
  • 4.6.空指针异常:
    在这里插入图片描述
    在这里插入图片描述

(7)万能的Map

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

接口中方法:

//     map查询用户
     User getUserById2(Map<String,Object> map);

xml配置文件:

<!--    map查询用户-->
    <select id="getUserById2" parameterType="map" resultType="user">
        select * from `user` where id=#{userId} and `name`=#{Name}
    </select>

测试:

    @Test
    public void getUserById2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("userId",1);
        map.put("Name","zhangsan");
        User userById = mapper.getUserById2(map);
        System.out.println(userById);
        sqlSession.close();
    }

在这里插入图片描述

  • Map传递参数,是在sql中取出key,sql中的参数可以任意写,但要和key对应。
  • 对象传递参数,是在sql中取对象的属性。
  • 只有一个基本类型参数的情况下,可以直接在sql中取到!
  • 多个参数用Map,或者注解
  • map相比起实体类,map可定制化参数。
    理解思想。

(8)模糊查询

重点是思想

 List<User> getUserLike(String value);
  <select id="getUserLike" parameterType="string" resultType="com.kuang.pojo.User">
        SELECT * FROM `user` where `name` like #{value}
  </select>
<!--   select * from `user` where `name` like "%"#{value}"%"-->
    @Test
    public void getUserLike(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userLike = mapper.getUserLike("%李%");
   //     List<User> userLike = mapper.getUserLike("李");
        for (User user : userLike) {
            System.out.println(user);
        }
        sqlSession.close();
    }

两种方式:要么在里面写死,通过参数传递符号,要么在sql里面拼接死。
即:

  • 1.java代码执行的时候,传递通配符%%
  • 2.在sql拼接中使用通配符(存在sql注入问题)

四、配置解析

如果不理解配置解析,mybatis只会增删改查,没什么用。 增删改查jdbc已经够了,配置解析及之后的内容才是需要掌握的。

(1)核心配置文件

  • mybatis-config.xml(随意命名,但官方推荐使用这个名字命名)
  • 该配置文件中包含了会深深影响myBatis行为的设置和属性信息
  • xml配置需要掌握的东西
    在这里插入图片描述
    • Properties掌握。
    • Settings掌握部分
    • typeAliases完全掌握。
    • environments和mappers掌握。
    • 其他了解即可。

在该配置文件中,标签放置的位置有一个规定的顺序,不能随意放置标签。

在这里插入图片描述

(2)环境配置(environments)

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
<!--                在xml文件中,&不能用,需要转义&amp。-->
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

这里知道:

  • 1.Mybatis中的事务管理器有两种,一种jdbc,一种managed。
    • jdbc可以进行事务的提交和回滚。
    • managed几乎并没有做什么。
  • 2.默认连接是连接池的实现。
  • 3.MyBatis可以配置多套环境。但每次只能选择一套。

(3)属性(Properties)

<!--    <properties resource="db.properties"/>-->
    <properties resource="db.properties">
<!--        <property name="username" value="root"/>-->
<!--        <property name="password" value="111111"/>-->
    </properties>

db.properties:

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

在这里插入图片描述

如果配置文件和新加入的属性都有同一个键,就存在优先级的问题。 相同的键,优先使用配置文件的。

(4)类型别名(typeAliases)

  • 类型别名可为 Java 类型设置一个别名。 它仅用于 XML 配置,仅在于降低完全限定名的冗余。
  • 两种实现方式:

方式一:直接给实体类起别名。

<!--    可以给实体类器别名-->
    <typeAliases>
        <typeAlias type="com.kuang.pojo.User" alias="User"/>
    </typeAliases>

方法二:可以指定一个包名,MyBatis会在该包下自动搜索需要的Java Bean。

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

<!--    可以给实体类器别名-->
    <typeAliases>
        <package name="com.kuang.pojo"/>
    </typeAliases>
    <select id="getUserList"  resultType="user">
        select * from mybatis.user
    </select>

  • 在实体类比较少的时候,使用第一种方式;如果实体类十分多,建议使用第二种。

第二种扫描包方式,在实体类中使用注解可以起别名,实现自定义别名。

@Alias("hello")
public class User{
    ...
}

  • 默认的一些别名:
    在这里插入图片描述
    在这里插入图片描述

    即基本数据类型别名是_基本数据类型,引用是直接首字母小写。

(5)设置(setting)

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

在这里插入图片描述
日志打印:
在这里插入图片描述
驼峰命名:
在这里插入图片描述

正常数据库和实体类的这样的字段是转换不了的,必须属性和字段对应。
Oracle数据库会把有驼峰的字段全部转换为大写,可读性及其低。因此之后就把字段用_来分割。

  • 一个配置完整的 settings 元素的示例如下:
<settings>
  <setting name="cacheEnabled" value="true"/>
  <setting name="lazyLoadingEnabled" value="true"/>
  <setting name="multipleResultSetsEnabled" value="true"/>
  <setting name="useColumnLabel" value="true"/>
  <setting name="useGeneratedKeys" value="false"/>
  <setting name="autoMappingBehavior" value="PARTIAL"/>
  <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
  <setting name="defaultExecutorType" value="SIMPLE"/>
  <setting name="defaultStatementTimeout" value="25"/>
  <setting name="defaultFetchSize" value="100"/>
  <setting name="safeRowBoundsEnabled" value="false"/>
  <setting name="mapUnderscoreToCamelCase" value="false"/>
  <setting name="localCacheScope" value="SESSION"/>
  <setting name="jdbcTypeForNull" value="OTHER"/>
  <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>

(6)其他配置(了解)

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

(7)映射器(mappers)

  • MapperRegistry:注册绑定我们的Mapper文件,每写一个dao层就要写一个Mapper文件。
  • 三种注册方式:

方式一:

<!--    路径以/代替-->
 <mapper resource="com/kuang/dao/UserMapper.xml"/>

方式二:

<!--    通过扫描类的方式:-->
  <mapper class="com.kuang.dao.UserMapper"/>

方式三:

<!--    通过包扫描的方式:-->
<package name="com.kuang.dao"/>
  • 方式一怎么用都可以。(推荐使用方式一)
  • 方式二和方式三的使用需要满足以下条件
    • 接口和他的Mapper配置文件必须同名
    • 接口和他的Mapper配置文件必须在同一个包下

(8)生命周期和作用域

在这里插入图片描述
生命周期,和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题。

  • SqlSessionFactoryBuilder:

    • 一旦创建了 SqlSessionFactory,就不再需要它了
    • 局部变量
  • SqlSessionFactory:

    • 类似于数据库连接池
    • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有 任何理由丢弃它或重新创建另一个实例
    • SqlSessionFactory 的最佳作用域是应用作用域。
    • 最简单的就是使用单例模式或者静态单例模式
  • SqlSession:

    • 连接到连接池的一个请求
    • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
    • 用完之后需要赶紧关闭,否则资源被占用!
      在这里插入图片描述

五、resultMap,解决属性名和字段名不一致的问题。

在这里插入图片描述
在这里插入图片描述
发现取不到数据。

解决方法:

  • 1.取别名:
    <select id="getUserById" parameterType="int" resultType="user">
        select id,name,pwd as password from mybatis.user where id=#{id}
    </select>
  • 2.resultMap结果集映射:

<!--id是resultMap取得一个名字,type仍然是返回值类型
什么字段和属性不一样就转哪个。
-->
<resultMap id="UserMap" type="user">
    <result column="pwd" property="password"/>
</resultMap>
        <select id="getUserById" parameterType="int" resultMap="UserMap">
            select * from mybatis.user where id=#{id}
        </select>
 - ResultMap 元素是 MyBatis 中最重要最强大的元素
 - ResultMap 的设计思想是,对简单的语句根本不需要配置显式的结果映射,对于复杂一点的语句,只需要描述语句之间的关系就行了
 - ResultMap 最优秀的地方在于,虽然你已经对它相当了解了,但是根本不需要显示的调用它们。

六、日志

(1)日志工厂

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

之前排错: sout,debug。现在:日志工厂
在这里插入图片描述
1、SLF4J
2、LOG4J(掌握)
3、LOG4J2
4、JDK_LOGGING JDK自带的日志工厂
5、COMMONS_LOGGING
6、STDOUT_LOGGING(掌握,标准日志输出)
7、NO_LOGGING

(2)STDOUT_LOGGING —标准日志输出

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

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

在这里插入图片描述

(3)LOG4J

3.1什么是log4j?

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

3.2配置log4j步骤

1.先导入log4j的包

    <dependency>
         <groupId>log4j</groupId>
         <artifactId>log4j</artifactId>
         <version>1.2.12</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 =  %d{ABSOLUTE} %5p %c{1}:%L - %m%n

### 文件输出相关配置 ###
log4j.appender.file = org.apache.log4j.FileAppender
log4j.appender.file.File = ./log/kuang.log

log4j.appender.file.Append = true
log4j.appender.file.Threshold = debug

log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 日志输出级别,logger后面的内容全部为jar包中所包含的包名 ###
log4j.logger.org.mybatis=debug
log4j.logger.java.sql=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


3.配置日志为log4j:

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

不能有空格,大小写也不能错。最好复制过来。

4.运行测试:

 @Test
    public void testlog4j() {
   		Logger logger = Logger.getLogger(UserDaoTest.class);
        logger.info("info:进入了testlog4j");
        logger.debug("debug:进入了testlog4j");
        logger.error("error:进入了testlog4j");
    }

在这里插入图片描述

5.简单使用:

  • 1.在要使用Log4j的类中,导入包
import org.apache.log4j.Logger;
  • 2.日志对象,参数为当前类的class
 static Logger logger = Logger.getLogger(UserDaoTest.class);
  • 3.输出日志级别
  logger.info("info:进入了testlog4j");
  logger.debug("debug:进入了testlog4j");
  logger.error("error:进入了testlog4j");

七、分页

当数据非常多时,分页可以减少数据的展现量与处理量。

(1)limit实现分页

SELECT * FROM user limit startIndex,pageSize;
SELECT * FROM user limit 0,2;
SELECT * FROM user limit n;#一个参数是[0,n]

//接口
List<User> getUserByLimit(Map<String,Integer> map);
<!--接口对应的xml-->
    <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<>();
    map.put("startIndex",1);
    map.put("pageSize",2);
    List<User> userList = mapper.getUserByLimit(map);
    for (User user : userList) {
        System.out.println(user);
    }

    sqlSession.close();

(2)RowBounds实现分页

了解即可,不推荐使用。

//接口
List<User> getUserByRowBounds();

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

@Test
public void getUserByRowBounds(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    //RowBounds实现
    RowBounds rowBounds = new RowBounds(1, 2);


    //通过java代码层面实现分页
    List<User> userList = sqlSession.selectList("com.kuang.dao.UserMapper.getUserByRowBounds",null,rowBounds);
    for (User user : userList) {
        System.out.println(user);
    }

    sqlSession.close();
}

(3)分页插件

MyBatis 分页插件 PageHelper

八、使用注解开发

(1)面向接口编程

一、概念

1.什么是面向接口编程?
面向接口编程就是先把客户的业务逻辑线提取出来,作为接口,业务具体实现通过该接口的实现类来完成。
当客户需求变化时,只需编写该业务逻辑的新的实现类,通过更改配置文件(例如Spring框架)中该接口
的实现类就可以完成需求,不需要改写现有代码,减少对系统的影响。
复制代码
2.面向接口编程的优点
1 降低程序的耦合性。其能够最大限度的解耦,所谓解耦既是解耦合的意思,它和耦合相对。耦合就是联系
,耦合越强,联系越紧密。在程序中紧密的联系并不是一件好的事情,因为两种事物之间联系越紧密,你更换
其中之一的难度就越大,扩展功能和debug的难度也就越大。
2 易于程序的扩展;
3 有利于程序的维护;
复制代码
3.接口编程在设计模式中的体现:开闭原则
其遵循的思想是: 对扩展开放,对修改关闭。其恰恰就是遵循的是使用接口来实现。在使用面向接口的编程过程
中,将具体逻辑与实现分开,减少了各个类之间的相互依赖,当各个类变化时,不需要对已经编写的系统进行
改动,添加新的实现类就可以了,不在担心新改动的类对系统的其他模块造成影响。

(2)使用注解开发

在这里插入图片描述
简单的语句可以用注解,复杂的就不能用了。

接口:


public interface UserMapper {
    @Select("select * from user")
    List<User> getUsers();
}

在Mybatis核心配置文件中绑定接口:

<!--绑定接口-->
    <mappers>
        <mapper class="com.qjd.dao.UserMapper"/>
    </mappers>

测试:

    @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();

    }

注解和配置文件可以一块用,但类和对应的xml文件必须同名而且在同一个包下
注解底层由反射机制+动态代理实现。
在这里插入图片描述

(3)Mybatis详细执行流程

在这里插入图片描述

  1. 建立Mybatis核心配置文件mybatis-config.xml
  2. 编写工具类MybatisUtils,读取该配置文件,并得到sqlsessionfactory
  3. 编写接口和对应的XML文件
  4. 测试

(4)注解实现CRUD

可以在工具类创建的时候实现自动提交事务
sqlSessionFactory.openSession(true);

public interface UserMapper {
    @Select("select * from user")
    List<User> getUsers();

    @Select("select * from user where id=#{uid}")
    User getUserById(@Param("uid") int id);

    @Insert("insert into user 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);

}

只有一个接口,要在配置中注册接口:

<mappers>
    <mapper class="com.kuang.dao.UserMapper"/>
</mappers>
    @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//        User userById = mapper.getUserById(1);
//        System.out.println(userById);

//        insert
//        mapper.addUser(new User(6,"令狐冲","123456"));
//        mapper.updateUser(new User(4,"任盈盈","123123"));
        mapper.deleteUser(3);
        sqlSession.commit();
        sqlSession.close();

    }

(5)其他

  • 1.@Param()注解:
    • 基本类型的参数或者String需要加上
    • 引用类型不需要加
    • 如果只有一个基本类型的话,可以忽略,但是建议大家都加上
    • 我们在sql中引用的就是我们这里的@Param(“”)中设定的属性名
      在这里插入图片描述
      即#{}里面的参数就对应的@Param里面的。就相当于跟你限定了一个名字,之后更改都以这个限定的名字为主。
  • 2.#{} 和 ${}
    • (1)#{}是预编译处理,$ {}是字符串替换
    • (2)mybatis在处理两个字符时,处理的方式也是不同的:
      • ​处理#{}时,会将sql中的#{}整体替换为占位符(即:?),调用PreparedStatement的set方法来赋值;
      • ​在处理 $ { } 时,就是把 ${ } 替换成变量的值。
  • 3.使用 #{} 可以有效的防止SQL注入,提高系统安全性:

在这里插入图片描述

九、Lombok

lombok可以:

在这里插入图片描述

使用步骤:

  1. 在IDEA中安装Lombok插件
    在这里插入图片描述
    如果没有就点中间的浏览器去找。在这里插入图片描述
    找到一个使用人数特别多的。
    在这里插入图片描述

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

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.10</version>

</dependency>

  1. 在实体类上加注解即可
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String password;
}

所有lombok能加的注解都在这里:

@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
@var
experimental @var
@UtilityClass

不支持构造器的重载,但构造器可以手动去加。
但lombok能不用就不用。

十、多对一的处理和一对多的处理

(1)测试环境搭建

1.新建实体类Teacher,Student

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, '秦老师'); 

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', '小李', '1'); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');

在这里插入图片描述

  1. 建立Mapper接口
public interface TeacherMapper {
    @Select("select *from teacher where id=#{tid}")
    Teacher getTeacher(@Param("tid") int id);
}

3.建立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.kuang.dao.TeacherMapper">

</mapper>

4.在核心配置文件中绑定注册我们的Mapper接口或者文件

<!--绑定接口-->
    <mappers>
        <mapper class="com.qjd.dao.StudentMapper"/>
        <mapper class="com.qjd.dao.TeacherMapper"/>
    </mappers>

  1. 测试查询是否能够成功
public class MyTest {

    public static void main(String[] args) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(1);
        System.out.println(teacher);    
        sqlSession.close();
    }
}

  • 结果映射(resultMap)
    • association映射对象
    • collection映射集合

(2)多对一的处理

public interface StudentMapper {
    //查询所有的学生信息以及对应的老师信息
    //方式一、按照查询嵌套处理
    public List<Student> getStudent();
    //    方式二、按照结果嵌套查询
    public List<Student> getStudent2();
}
public class Student {
    private int id;
    private String name;
//    每个学生对应1个老师
    private Teacher teacher;
}
public class Teacher {
    private int id;
    private String name;
}

学生和老师

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

1.按照查询嵌套处理(类似于子查询)

<select id="getStudent" resultMap="StudentTeacher">
    select * from student
</select>
    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <collection property="teacher" javaType="Teacher" column="tid" select="getTeacherByStudentTid"/>
    </resultMap>


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

在这里插入图片描述

  • association映射对象。这里也可以用association
    在这里插入图片描述

2.按照结果映射

现在像直接用这条语句查,不分开

select s.id sid,s.name sname,t.name tname,t.id tid from student s,teacher t where s.tid=t.id

在这里插入图片描述

    <select id="getStudent2" resultMap="StudentTeacher2">
        select s.id sid,s.name sname,t.name tname,t.id tid 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="id" column="tid"/>
            <result property="name" column="tname"/>
        </association>
    </resultMap>

在这里插入图片描述
建议使用按照结果进行映射的方式,第一种比较绕。但每个人的情况不一样。

(3)一对多的处理

一个老师对应多名学生:
在这里插入图片描述

1.方式一、按照结果映射

<select id="getTeacherById" resultMap="TeacherStudent">
    select s.id sid,s.`name` sname,t.`name` tname,t.id tid from teacher t,student s where t.id=s.tid  and t.id=#{tid}
</select>
    <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"/>
        </collection>
    </resultMap>

在这里插入图片描述
collection映射集合

2.方式二、按照查询嵌套处理

    <select id="getTeacherById2" 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="students" javaType="ArrayList" ofType="Student" column="id" select="getStudentByTeacherId"/>
    </resultMap>
    <select id="getStudentByTeacherId" resultType="Student">
        select * from student where tid=#{id}
    </select>

(3)建立Mapper.xml文件的步骤

1.创建一个实体类对应的xml文件

在这里插入图片描述
2.复制mybatis核心配置文件mybatis-config.xml到该文件中,并只保留头部
在这里插入图片描述
3.更改config为mapper
在这里插入图片描述
4.如图
在这里插入图片描述

十一、动态SQL

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

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

动态sql相关的标签:

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

(1)环境搭建

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

2.创建一个基础工程

导包、配置文件、实体类、工具类、实体类对应的Mapper接口和Mapper.xml文件、测试。

2.1工具类IDutils :

public class IDutils {
    public static String getId() {
        return UUID.randomUUID().toString().replace("-","");
    }

   @Test
    public void test() {
        System.out.println(IDutils.getId());
        System.out.println(IDutils.getId());
        System.out.println(IDutils.getId());
    }
}

2.2 驼峰命名

<setting name="mapUnderscoreToCamelCase" value="true"/>

(2)IF标签

需求:查询某个title就传某个title,查询某个author就传某个author,什么都没传就查询所有。

接口:

//查询博客
    List<Blog> queryBlogIf(Map map);

xml文件:

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

测试:

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

        sqlSession.close();
    }
  1. if标签可对传入的值进行条件判断
  2. 这里的where 1=1是不正规的
  3. 这样sql语句没有变,可以通过不同的参数实现一个动态的效果。
    在这里插入图片描述

官方文档上的东西不易于理解,这些东西的学习方式是把它的一些东西剖析成自己的一些东西。

(3)choose、when、otherwise组合

如果现在需求又变了,title、views和author只查其中一个。

在这里插入图片描述
接口:

 List<Blog> queryBlogChoose(Map map);

xml文件:

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

    </select>

测试:

    @Test
    public void queryBlogChoose() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("author","狂神说");
        map.put("title","微服务如此简单");
        map.put("views",1000);
        List<Blog> blogs = mapper.queryBlogChoose(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }

        sqlSession.close();
    }

类似于switch,case 当满足条件时,就匹配对应的语句,且只匹配1个case。

(4)trim(where、set)

where和set有个总的标签叫trim,但一般不用总的标签。

4.1 where

在这里插入图片描述
在这里插入图片描述

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

更改这个sql语句为:

    <select id="queryBlogIf" 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用标签替换后开头多余的and或or会自动去除。
  • 如果什么都不传,where标签也会自动去除。

4.2 set

set类似于where,会自动删除后面的逗号。

在这里插入图片描述
接口:

//    更新博客
    int updateBlog(Map map);

xml文件:

    <update id="updateBlog" parameterType="map">

        update blog
        <set>
            <if test="title!=null">
                title = #{title},
            </if>
            <if test="author!=null">
                author=#{author}
            </if>
        </set>
        where id =#{id}

    </update>

测试:

    @Test
    public void updateBlog() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap<String, Object> map = new HashMap<String, Object>();
//        map.put("author","狂神说333");
        map.put("title","微服务如此简单3334");
        map.put("id","459863eb5c4a4e5e929a5beb8c27afec");
        mapper.updateBlog(map);

        sqlSession.commit();
        sqlSession.close();
    }

4.3 trim

一般where和set就够用了,很少再用这个定制化。

在这里插入图片描述
在这里插入图片描述

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

(5)SQL片段

  1. 使用sql标签抽取公共部分
  2. 在需要使用的地方使用include标签引用即可
<!--    sql代码片段-->
    <sql id="if-title-author">
        <if test="title !=null">
            and title=#{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
    </sql>
    <select id="queryBlogIfSql" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <include refid="if-title-author"></include>
        </where>

    </select>

注意事项:

  • 最好基于单表来定义sql片段。
  • 不要在SQL片段中使用where标签。

sql语句里面不要做一些太复制的事情,复杂的事情重用的效率就变低了。 因此包含的时候尽量只要一些if判断就好了。

(6)foreach标签

现在要查一些特殊的查询。比如只查表中的123号人。
在这里插入图片描述

例如要查这个语句:

select * from blog where 1=1 and (id=1 or id=2 or id=3);

Id=1 or id=2 or id=3在动态sql里面只能通过foreach。
接口:

//foreach
    List<Blog> queryBolgForeach(Map map);

xml文件:

<!--    foreach-->
    <select id="queryBolgForeach" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <foreach collection="ids" item="id" open="(" close=")" separator="or">
                id=#{id}
            </foreach>
        </where>
    </select>

map中put一个集合传参,作为foreach中的集合ids。

索引index一般用不到。
测试:

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

        sqlSession.close();
    }
  • 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。
  • 当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。
  • 当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

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

  • 可以先在Mysql中写出完整的SQL语句,语法正确后,再对应去修改成动态SQL实现通用即可。

十二、缓存(了解)

(1)简介

1.什么是缓存?

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

2.为什么使用缓存?

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

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

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

(2)MyBatis缓存

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

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

    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
    • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
    • 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
      在这里插入图片描述
      在这里插入图片描述
  • sqlSession级别:一个SqlSession从获取到关闭的过程。

  • namespace级别:一个mapper接口中的所有的SqlSession。

(3)一级缓存

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

测试步骤:

  1. 开启日志
  2. 测试在Session中查询两次相同的记录
@Test
public void  test(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    User user = mapper.queryUserById(1);
    System.out.println(user);
    System.out.println("=================================================================");
    User user2 = mapper.queryUserById(1);
    System.out.println(user2);

    System.out.println(user==user2);

    sqlSession.close();
}

  • 查看日志输出
    在这里插入图片描述
  • 缓存失效
    • 1.查询不同的东西。(方法)
    • 2.增删改操作,可能会改变原来的数据,所以必定会刷新缓存。
    • 3.查询不同的Mapper.xml。
    • 4.手动清理缓存。
      在这里插入图片描述

一级缓存只有在连续查询相同的一个时,才有点用。比如说用户不停的在刷新一个页面,不停的查询时。

小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段(相当于一个用户不断查询相同的数据,比如不断刷新),一级缓存就是一个map。

(4)二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存。
  • 基于namespace级别的缓存,一个名称空间(接口),对应一个二级缓存。
  • 工作机制
    • 一个会话(用户)查询一条数据,这个数据就会被放在当前会话的一级缓存中。
    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
    • 新的会话查询信息,就可以从二级缓存中获取内容。
    • 不同的mapper查出的数据会放在自己对应的缓存(map)中。

步骤

1.开启全局缓存(settings)
在mybatis核心配置文件mybatis-config.xml中设置:

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

2.在要使用二级缓存的Mapper中开启

 <cache/>

​ 可以不加参数,也可以自定义参数:

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

3.测试

@Test
public void  test(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    SqlSession sqlSession2 = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    User user = mapper.queryUserById(1);
    System.out.println(user);
    sqlSession.close();
    
    UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
    User user2 = mapper.queryUserById(1);
    System.out.println(user2);
    sqlSession2.close();
    
    System.out.println(user==user2);
}

4.结果
在这里插入图片描述
可以看到只运行一次sql

单个查询中也可以使用缓存,增删改也可以设置不刷新缓存:
在这里插入图片描述

问题:

  • 1.我们需要将实体类序列化(实现Serializable接口),否则就会报错
  • 2.sqlsession关闭的时候一定要在最后关闭,不能先关闭sqlsession再关闭sqlsession2,这样会导致Cause: org.apache.ibatis.executor.ExecutorException: Executor was closed

4.小结

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

(5)Mybatis缓存原理

在这里插入图片描述
1.程序中:

  • 第一次查询走数据库,当第一次查询完结果放到一级缓存中,第二次就走一级缓存了。
  • 当每一个sqlSession关闭的时候,对应一级缓存中的东西就会转移到对应Mapper的二级缓存中。

2.用户访问时,正确的顺序应该是:

  • 1.先看二级缓存中有没有
  • 2.再看一级缓存中有没有
  • 3.查询数据库

(6)自定义缓存

介绍:

  • EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
  • Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存。

1.要在程序中使用ehcache,先要导包:

<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.1.0</version>
</dependency>

2.在mapper中指定使用我们的ehcache缓存实现:

<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

这部分关于缓存的内容了解就可以,以后开发我们会用Redis数据库来做缓存!

十三、错误总结

在这里插入图片描述
在这里插入图片描述

  • 33
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值