Mybatis

前言

本博客根据b站狂神说Mybatis课程,视频如下:
Mybatis视频链接

官方文档

MyBatis官方文档:https://mybatis.org/mybatis-3/zh/index.html

一、简介

1.1 什么是mybatis

简介
什么是 MyBatis?

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

如何获得MyBatis?
Maven仓库:

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

github:https://github.com/mybatis/mybatis-3/releases

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

1.2 持久化

数据持久化

持久化就是将程序的数据在持久状态和瞬时状态转化的过程
内存:断电即失
数据库(JDBC),io文件持久化。
生活:冷藏、罐头。

为什么需要持久化?

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

1.3 持久层

Dao层、Service层、Controller层…

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

1.4 为什么需要mybatis

帮助程序员将数据存入到数据库中。

方便

传统的JDBC代码太复杂了。简化、框架、自动化。

不用Mybatis也可以。更容易上手。技术没有高低之分

优点:
    简单易学
    灵活
    sql和代码的分离,提高了可维护性。
    提供映射标签,支持对象与数据库的orm字段关系映射
    提供对象关系映射标签,支持对象关系组建维护
    提供xml标签,支持编写动态sql。

最重要的一点:使用的人多!

Spring SpringMVC SpringBoot

二、第一个Mybatis程序

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

2.1 搭建环境

CREATE DATABASE mybatis;
use mybatis;
CREATE TABLE user(
id INT(20) not null PRIMARY KEY,
name VARCHAR(30) DEFAULT NULL,
pwd VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;


INSERT INTO USER (`id`,`name`,`pwd`) VALUES
(1,"狂神","123456"),(2,"张三","123456"),(3,"李四","123890");

在这里插入图片描述

新建Maven项目
新建一个普通的maven项目
删除src目录

在这里插入图片描述在这里插入图片描述导入maven依赖

        <!--mysql驱动        -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <!--mybatis        -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>

        <!--测试 junit        -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>

为了resource中资源好下载,最要也加入这个依赖

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

2.2 创建一个模块(子项目)

在Maven Mybatis中创建Maven子项目Mybatis-01
在这里插入图片描述
编写mybatis的核心配置文件(见官方文档:https://mybatis.org/mybatis-3/zh/index.html

在这里插入图片描述
一定要注意:现在要写成:value=com.mysql.cj.jdbc.Driver

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=GMT%2B8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <!--每个Mapper.xml都需要在Mybatis核心配置文件中进行注册  -->
    <mappers>
        <mapper resource="com/kuang/dao/UserMapper.xml"/>
    </mappers>
</configuration>

2.3 构建工具类

构建工具类,实现链接mysql 并且获得SqlSessionFactory,进一步从中获得 SqlSession 的实例

在这里插入图片描述

在这里插入图片描述

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   见官方文档
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try { //使用Mybatis第一步,创建SqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
    // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法
    public static SqlSession getSqlSession(){
        /*
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
         */
        return sqlSessionFactory.openSession();
    }
}

2.4 编写代码

  • 实体类
    在这里插入图片描述
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 + '\'' +
                '}';
    }
}


  • Dao接口

在这里插入图片描述

package com.kuang.dao;

import com.kuang.pojo.User;

import java.util.List;

public interface UserDao {
    public List<User> getUserList();
}


  • 实现Dao接口

接口实现类由原来的UserImpl转变为一个Mapper配置文件

在这里插入图片描述

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个对应的Dao/Mapper接口  原理相当于原来写一个UserDaoImpl实现UserDao接口-->
<mapper namespace="com.kuang.dao.UserDao">
    <!--查询语句    -->
    <!--id="getUserList"相当于重写了 com.kuang.dao.UserDao中的 getUserList方法  -->
    <!--返回的结果应该List<User>,这里写里面的泛型就可以   -->
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from mybatis.user;
    </select>
</mapper>

2.5 测试

import com.kuang.dao.UserDao;
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 testDemo() {
        //第一步,获取sqlSession实例
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        //第二步  执行sql
        // 方式一:getMapper
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
}

在这里插入图片描述

注意事项:
一、
测试的时候出现这个报错:
org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.

一定要在Mybatis-config.xml 配置Mapper
在这里插入图片描述

  <!--每个Mapper.xml都需要在Mybatis核心配置文件中进行注册  -->
    <mappers>
        <mapper resource="com/kuang/dao/UserMapper.xml"/>
    </mappers>

**二、**无法获得Mapper.xml

在这里插入图片描述
原因是将UserMapper.xml放在了dao层下,没有放在resources目录下,无法加载配置文件,解决方法是在pom.xml中添加如下配置:

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

三、CRUD

3.1、namespace

  • 将上面案例中的UserMapper接口改名为 UserDao;
  • 将UserMapper.xml中的namespace改为为UserDao的路径 .
  • 再次测试

结论:

配置文件中namespace中的名称为对应Mapper接口或者Dao接口的完整包名,必须一致!

3.2、select

  • select标签是mybatis中最常用的标签之一
  • select语句有很多属性可以详细配置每一条SQL语句
    • id

      • 命名空间中唯一的标识符
      • 接口中的方法名与映射文件中的SQL语句ID 一一对应
    • parameterType

      • 传入SQL语句的参数类型 。【万能的Map,可以多尝试使用】
    • resultType

      • SQL语句返回值类型。【完整的类名或者别名】

需求:根据id查询用户
UserMapper中添加对应方法

    //根据id得到用户
    public User getUserById(int id);

UserMapper.xml添加select

    <select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User">
        <!--为什么要这样写${id} 因为UserMapper中 写的:public User getUserById(int id);       -->
        select * from mybatis.user where id = ${id}
    </select>

UserMapperTest中添加测试方法

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

3.3、insert

一般使用insert标签进行插入操作,它的配置和select标签差不多!
需求:给数据库增加一个用户
UserMapper中添加对应方法

    //添加用户
    public int addUser(User user);

UserMapper.xml添加insert

    <!--插入用户  其中对象User中得属性,可以直接取出来#{id} #{name} #{pwd}-->
    <select id="addUser" parameterType="com.kuang.pojo.User" resultType="int">
        insert into user (id, name, pwd) values(#{id}, #{name}, #{pwd})
    </select>

UserMapperTest中添加测试方法

    @Test
    public void addUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        int res = userMapper.addUser(new User(4, "赵六", "123456"));
        if (res > 0) System.out.println("插入成功");
        sqlSession.commit();
        sqlSession.close();
    }

3.4、Update

我们一般使用update标签进行更新操作,它的配置和select标签差不多!
需求:修改用户的信息
UserMapper中添加对应方法

    int updateUser(User user);

UserMapper.xml添加update

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

UserMapperTest中添加测试方法

    @Test
    public void updateUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        int res = userMapper.updateUser(new User(4, "赵五", "123456"));
        if (res > 0) System.out.println("更新成功");
        sqlSession.commit();
        sqlSession.close();
    }

3.5、Delete

我们一般使用delete标签进行删除操作,它的配置和select标签差不多!
需求:根据id删除一个用户

UserMapper中添加对应方法

    int deleteUser(int id);

UserMapper.xml添加update

    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id}
    </delete>

UserMapperTest中添加测试方法

    @Test
    public void deleteUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        int res = userMapper.deleteUser(4);
        if (res > 0) System.out.println("删除成功");
        sqlSession.commit();
        sqlSession.close();
    }

  • List item

小结:

  • 所有的增删改操作都需要提交事务!
  • 接口所有的普通参数,尽量都写上@Param参数,尤其是多个参数时,必须写上!
  • 有时候根据业务的需求,可以考虑使用map传递参数!
  • 为了规范操作,在SQL的配置文件中,我们尽量将Parameter参数和resultType都写上!

3.6、万能Map

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

Map传递参数,直接在sql中取出key即可 【】

    <insert id="addUser2" parameterType="map" >
        insert into user (id, name, pwd) values(#{userid}, #{userName}, #{password})
    </insert>
    int addUser2(Map<String, Object> map);
    @Test
    public void addUser2() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        Map<String, Object> map = new HashMap<>();
        map.put("userid",4);
        map.put("userName", "赵六");
        map.put("password", "123456");
        int res = userMapper.addUser2(map);
        if (res > 0) System.out.println("插入成功");
        sqlSession.commit();
        sqlSession.close();
    }


3.7、模糊查询

模糊查询like语句该怎么写?

第1种:在Java代码中添加sql通配符。

string wildcardname =%smi%;
list<name> names = mapper.selectlike(wildcardname);
<select id=”selectlike”>
 select * from foo where bar like #{value}
</select>

第2种:在sql语句中拼接通配符,会引起sql注入

string wildcardname = “smi”;
list<name> names = mapper.selectlike(wildcardname);
<select id=”selectlike”>
     select * from foo where bar like "%"#{value}"%"
</select>

3.8、思考

四、配置解析(重要)

Mybatis官方文档:https://mybatis.org/mybatis-3/zh/index.html

在这里插入图片描述

4.1、核心配置文件

  • mybatis-config.xml 系统核心配置文件
  • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。
  • 能配置的内容如下:(注意元素节点的顺序!顺序不对会报错 )
configuration(配置)
    properties(属性)
    settings(设置)
    typeAliases(类型别名)
    typeHandlers(类型处理器)
    objectFactory(对象工厂)
    plugins(插件)
    environments(环境配置)
        environment(环境变量)
            transactionManager(事务管理器)
            dataSource(数据源)
    databaseIdProvider(数据库厂商标识)
    mappers(映射器)
<!-- 注意元素节点的顺序!顺序不对会报错 -->

4.2、environments元素

<environments default="development">
  <environment id="development">
    <transactionManager type="JDBC">
      <property name="..." value="..."/>
    </transactionManager>
    <dataSource type="POOLED">
      <property name="driver" value="${driver}"/>
      <property name="url" value="${url}"/>
      <property name="username" value="${username}"/>
      <property name="password" value="${password}"/>
    </dataSource>
  </environment>
</environments>

配置MyBatis的多套运行环境,将SQL映射到多个不同的数据库上,必须指定其中一个为默认运行环境(通过default指定)

子元素节点:environment

具体的一套环境,通过设置id进行区别,id保证唯一!

  • 子元素节点:transactionManager - [ 事务管理器 ]
  • 子元素节点:数据源(dataSource)
    • type="[UNPOOLED|POOLED|JNDI]")
    • unpooled: 这个数据源的实现只是每次被请求时打开和关闭连接。
    • pooled: 这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来 , 这是一种使得并发 Web
      应用快速响应请求的流行处理方式。
    • jndi:这个数据源的实现是为了能在如 Spring 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个 JNDI
      上下文的引用。
    • 数据源也有很多第三方的实现,比如dbcp,c3p0,druid等等…

.

4.3、mappers元素

4.3.1、mpaaers

  • 映射器 : 定义映射SQL语句文件
  • 既然 MyBatis 的行为其他元素已经配置完了,我们现在就要定义 SQL 映射语句了。但是首先我们需要告诉 MyBatis
    到哪里去找到这些语句。 Java 在自动查找这方面没有提供一个很好的方法,所以最佳的方式是告诉 MyBatis
    到哪里去找映射文件。你可以使用相对于类路径的资源引用, 或完全限定资源定位符(包括 file:/// 的
    URL),或类名和包名等。映射器是MyBatis中最核心的组件之一,在MyBatis
    3之前,只支持xml映射器,即:所有的SQL语句都必须在xml文件中配置。而从MyBatis
    3开始,还支持接口映射器,这种映射器方式允许以Java代码的方式注解定义SQL语句,非常简洁。

4.3.2、引入资源方式

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

<mappers>
     <mapper resource="com/princehan/dao/UserMapper.xml"/>
</mappers>

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

<mappers>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
</mappers>

方式三:使用映射器接口实现类的完全限定类名

<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
</mappers>

注意点:

  • 接口和它的Mapper配置文件必须同名
  • 接口和它的Mapper配置文件,并且位于同一目录下

方式四: 使用包名

<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

4.3.3、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">
<mapper namespace="com.princehan.dao.UserMapper">

</mapper>

  • namespace中文意思:命名空间,作用如下:
    • namespace和子元素的id联合保证唯一 , 区别不同的mapper

    • 绑定DAO接口

      • namespace的命名必须跟某个接口同名
      • 接口中的方法与映射文件中sql语句id应该一一对应
    • namespace命名规则 : 包名+类名

4.4、Properties优化

数据库这些属性都是可外部配置且可动态替换的,既可以在典型的 Java 属性文件中配置,亦可通过 properties 元素的子元素来传递。
具体可参考官方文档:https://mybatis.org/mybatis-3/zh/configuration.html#environments

<!--外层优先级最大-->
    <properties resource="db.properties">
        <property name="username" value="dev_user"/>
        <property name="password" value="F2Fa3!33TYyg"/>
    </properties>
  • 可以直接引入外部文件
  • 可以在其中增加一些属性配置
  • 如果两个文件有同一个字段,优先使用外部配置文件的。

优化我们的配置文件:
第一步 :在资源目录下新建一个db.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
username=root
password=123456

第二步 : 将文件导入properties 配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--导入properties文件-->
    <properties resource="db.properties"/>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/kuang/dao/UserMapper.xml"/>
    </mappers>
</configuration>

4.5、typeAliases优化

类型别名是为 Java 类型设置一个短的名字。它只和 XML 配置有关,存在的意义仅在于用来减少类完全限定名的冗余。

方法一:

<!--配置别名,注意顺序-->
<typeAliases>
    <typeAlias type="com.kuang.pojo.User" alias="User"/>
</typeAliases>

当这样配置时,User可以用在任何使用com.kuang.pojo.User的地方。

方法二:
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:

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

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

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

在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。

第一种自定义别名,第二种不行,如果需要改,需要在实体上增加注解。见下面的例子:

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

例如,使用了方法二:
在这里插入图片描述

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

4.6、其他配置浏览

是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。
设置中各项设置的含义、默认值等:settings

  • 懒加载
  • 日志实现
  • 缓存开启关闭

一个配置完整的 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>

4.7、生命周期和作用域

我们目前已经讨论过的不同作用域和生命周期类是至关重要的,因为错误的使用会导致非常严重的并发问题

我们可以先画一个流程图,分析一下Mybatis的执行过程!
在这里插入图片描述作用域理解:

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

在这里插入图片描述

五、ResultMap

思考:假如实体类属性名和数据库中字段名不一致会出现什么情况?

  • 新建一个Maven Module,拷贝之前的项目
  • 改写User实体类中的属性
package com.princehan.pojo;

public class User {
    private int id;
    private String name;
    private String password;
}
  • User表字段名
    在这里插入图片描述测试会出现何种情况?
<select id="getUserById" resultType="User" parameterType="int">
    select * from user where id = #{id}
</select>

在这里插入图片描述可以看到属性与字段名不一致会导致无法取出值。

分析

  • select * from user where id = #{id} 可以看做
  • select id,name,pwd from user where id = #{id}
  • MyBatis会根据这些查询的列名(会将列名转化为小写,数据库不区分大小写) , 去对应的实体类中查找相应列名的set方法设值 ,
    由于找不到setPwd() , 所以password返回null ; 【自动映射】

解决方法:

  1. 给字段名起别名
<select id="getUserById" resultType="User" parameterType="int">
    select id, name, pwd password from user where id = #{id}
</select>
  1. 使用ResultMap结果映射
<!--id="UserMap" 对应下面的resultMap="UserMap" column 对应数据库中的列 property代表实体类中的属性值-->
<resultMap id="UserMap" type="User">
    <id column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" resultMap="UserMap">
    select * from user where id = #{id}
</select>

5.1、ResultMap

5.1.1、自动映射

  • resultMap 元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets数据提取代码中解放出来。
  • 实际上,在为一些比如连接的复杂语句编写映射代码的时候,一份 resultMap 能够代替实现同等功能的长达数千行的代码。
  • ResultMap 的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。
<select id="selectUserById" resultType="map">
    select id , name , pwd 
    from user 
    where id = #{id}
</select>

上述语句只是简单地将所有的列映射到HashMap 的键上,这由 resultType属性指定。虽然在大部分情况下都够用,但是 HashMap不是一个很好的模型。你的程序更可能会使用 JavaBean 或 POJO(Plain Old Java Objects,普通老式 Java 对象)作为模型。

ResultMap 最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们。

5.1.2、手动映射

编写resultMap,实现手动映射!

<resultMap id="UserMap" type="User">
    <!-- id为主键 -->
    <id column="id" property="id"/>
    <!-- column是数据库表的列名 , property是对应实体类的属性名 -->
    <result column="name" property="name"/>
    <result column="pwd" property="password"/>
</resultMap>

返回值类型为resultMap

<select id="selectUserById" resultMap="UserMap">
    select id , name , pwd from user where id = #{id}
</select>

如需学习更多相关知识查看官方文档ResultMap的知识。

六、日志

6.1、日志工厂

思考:我们在测试SQL的时候,要是能够在控制台输出 SQL 的话,是不是就能够有更快的排错效率?

如果一个 数据库相关的操作出现了问题,我们可以根据输出的SQL语句快速排查问题。

对于以往的开发过程,我们会经常使用到debug模式来调节,跟踪我们的代码执行过程。但是现在使用Mybatis是基于接口,配置文件的源代码执行过程。因此,我们必须选择日志工具来作为我们开发,调节程序的工具。

Mybatis内置的日志工厂提供日志功能,具体的日志实现有以下几种工具:
在这里插入图片描述

  • SLF4J
  • Apache Commons Logging
  • Log4j 2
  • Log4j
  • JDK logging

具体选择哪个日志实现工具由MyBatis的内置日志工厂确定。它会使用最先找到的(按上文列举的顺序查找)。 如果一个都未找到,日志功能就会被禁用。

标准日志实现
指定 MyBatis 应该使用哪个日志记录实现。如果此设置不存在,则会自动发现日志记录实现。

6.2、Log4j

简介:

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

使用步骤:

  • 导入Log4j的依赖
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
  • 编写配置文件

在这里插入图片描述

#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/princehan.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH:mm:ss}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

setting设置日志实现

在这里插入图片描述

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

在程序中使用Log4j进行输出!

package com.princehan.dao;

import com.princehan.pojo.User;
import com.princehan.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;


public class UserMapperTest {

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

    @Test
    public void testLog4j() {
        logger.info("info:进入了testLog4j");
        logger.debug("debug:进入了testLog4j");
        logger.error("error:进入了testLog4j");
    }
}

在这里插入图片描述

项目目录下生成一个日志目录

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

  • 使用Log4j 输出日志
  • 可以看到还生成了一个日志的文件 【需要修改file的日志级别】

七、分页

思考:为什么需要分页?

在学习mybatis等持久层框架的时候,会经常对数据进行增删改查操作,使用最多的是对数据库进行查询操作,如果查询大量数据的时候,我们往往使用分页进行查询,也就是每次处理小部分数据,这样对数据库压力就在可控范围内。

7.1、使用Limit分页

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

UserMapper

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

测试类

package com.princehan.dao;

import com.princehan.pojo.User;
import com.princehan.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class UserMapperTest {

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

八、使用注解开发(不推荐)

8.1、设置自动提交事物

在这里插入图片描述

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

8.2、使用注解实现CRUD

  1. 使用注解可以不用mapper.xml,相应的也不需在mybatis-config.xml配置mapper.xml的映射,但仍需配置dao层接口。

    • mybatis-config.xml中配置
    <!--绑定接口-->
    <mappers>
        <mapper class="com.princehan.dao.UserMapper"/>
    </mappers>

  1. 编写接口
package com.princehan.dao;

import com.princehan.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;


public interface UserMapper {
    @Select("select id, name, pwd password from user")
    List<User> getUsers();

    //多个参数要用 @Param()
    @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 = #{uid}")//如果加@Param()要与里面的key相同
    int deleteUser(@Param("uid") int id);
}
  1. 编写测试类
@Test
    public void getUsers() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = userMapper.getUsers();
        for (User user : users) {
            System.out.println(user);
        }
        sqlSession.close();
    }

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

    @Test
    public void addUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.addUser(new User(6, "孙八", "123456"));
        sqlSession.close();
    }

    @Test
    public void updateUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.updateUser(new User(6, "孙八", "123456"));
        sqlSession.close();
    }

    @Test
    public void deleteUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.deleteUser(6);
        sqlSession.close();
    }

8.3、关于@Param()注解

@Param注解用于给方法参数起一个名字。以下是总结的使用原则:

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不用加
  • 在方法只接受一个参数的情况下,可以不使用==@Param==。
  • 在方法接受多个参数的情况下,建议一定要使用==@Param==注解给参数命名。
  • SQL中引用的就是==@Param==中设置的属性名

8.4、#{}与${}的区别

  • ${} 进行的是字符串的替换,在配置MyBatis连接数据库的时候用到,有SQL注入的风险。
    • 例如:order by #{parameterName} //或取Map中的value#{Key}也是一样操作。
      假设传入参数是“Smith”
      会解析成:order by Smith
  • #{}将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。keyi防止SQL注入
    • 例如:order by #{parameterName} //或取Map中的value#{Key}也是一样操作。
      假设传入参数是“Smith”
      会解析成:order by “Smith”

九、Lombok使用

Lombok项目是一个java库,它可以自动插入到编辑器和构建工具中,增强java的性能。不需要再写getter、setter或equals方法,只要有一个注解,你的类就有一个功能齐全的构建器、自动记录变量等等。

使用步骤:

  1. 在IDEA中安装Lombok插件

在这里插入图片描述

  1. 在项目中导入Lombok
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.26</version>
</dependency>
@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 config system
Code inspections
Refactoring actions (lombok and delombok)

说明:在实体类上加入注解或者属性上加入注解

@Data:无参构造、get、set、toString、hashcode、equals
@AllArgsConstructor:成成全参数构造函数
@NoArgsConstructor:生成无参构造函数

九、多对一处理

多对一的理解:

  • 多个学生对应一个老师
  • 如果对于学生这边,就是一个多对一的现象,即从学生这边关联一个老师!

9.1 环境搭建

数据库设计

在这里插入图片描述

CREATE TABLE `teacher` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

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

CREATE TABLE `student` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  `tid` INT(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fktid` (`tid`),
  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');

导入LomBok依赖

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

新建实体类(用LomBok创建)

  • Student
package com.princehan.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor

public class Student {
        private int id;
        private String name;
        private Teacher teacher;

}

  • Teacher
package com.princehan.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.ibatis.annotations.ConstructorArgs;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher {
        private int id;
        private String name;
        
}

mybatis-config.xml核心配置文件中绑定接口

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

编写测试类

package com.princehan.dao;

import com.princehan.pojo.Teacher;
import com.princehan.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/10 10:49
 */
public class MyTest {
    @Test
    public void getTeacher() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(1);
        System.out.println(teacher);
        sqlSession.close();
    }
    @Test
    public void getStudents() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> students = mapper.getStudents1();
        for (Student student : students) {
            System.out.println(student);
        }
        sqlSession.close();
    }
}

9.2、按照查询嵌套子查询(子查询)

<resultMap id="StudentTeacher" type="Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <!--复杂的属性 单独处理 对象 association 集合 collection-->
    <!--javatype 类型 select 子类型-->
    <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>

在这里插入图片描述

9.3、按照结果嵌套查询(联表查询)(用这个)

<!--按照结果嵌套子查询-->
    <select id="getStudents2" 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="name" column="tname"/>
            <result property="id" column="tid"/>
        </association>
    </resultMap>
    <!---->
    @Test
    public void getStudents2() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> students = mapper.getStudents2();
        for (Student student : students) {
            System.out.println(student);
        }
        sqlSession.close();
    }

在这里插入图片描述

十、多对一处理

一对多的理解

  • 一个老师拥有多个学生
  • 如果对于老师这边,就是一个一对多的现象,即从一个老师下面拥有一群学生(集合)!

10.1、环境搭建

编写实体类

package com.princehan.pojo;

import lombok.Data;

import java.util.List;

@Data
public class Teacher {
    private int id;
    private String name;
    private List<Student> students;
}

package com.princehan.pojo;

import lombok.Data;

/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/10 18:28
 */
@Data
public class Student {
    private int id;
    private String name;
    private int tid;

}

TeacherMapper

package com.princehan.dao;

import com.princehan.pojo.Teacher;
import org.apache.ibatis.annotations.Param;


public interface TeacherMapper {

    //查询指定老师下的学生及老师信息
    Teacher getTeacher(@Param("tid") int id);
    Teacher getTeacher2(@Param("tid") int id);
}

10.2、按照查询嵌套子查询

<!--按查询嵌套查询-->
    <select id="getTeacher2" resultMap="TeacherStudent2">
        select *
        from teacher
        where id = #{tid}
    </select>
    <resultMap id="TeacherStudent2" type="Teacher">
    	<!--javaType="List" ArrayList List也可以-->
        <!--ofType="Student"也可省略-->
        <collection property="students"
                    javaType="ArrayList"
                    ofType="Student"
                    select="getStudentByTeacherId"
                    column="id"
        />
    </resultMap>
    <select id="getStudentByTeacherId" resultType="Student">
        select *
        from student
        where tid = #{tid}
    </select>
    <!---->
    @Test
    public void getTeacher2() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher2(1);
        System.out.println(teacher);
        sqlSession.close();
    }

10.3、按照结果嵌套查询(用这个)

<!--按结果嵌套查询-->
    <select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid, s.name sname, t.name tname, t.id tid
        from student s,
             teacher t
        where s.tid = tid
          and tid = #{tid}
    </select>
    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--复杂属性用collection
        javaType=""指定属性的类型
        集合中的泛型信息,要用ofType获取-->
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>
    <!---->
    @Test
    public void getTeacher() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(1);
        System.out.println(teacher);
        sqlSession.close();
    }

在这里插入图片描述

10.4、小结

关联 - association
集合 - collection

所以association是用于一对一和多对一,而collection是用于一对多的关系

JavaTypeofType都是用来指定对象类型的
JavaType是用来指定pojo中属性的类型
ofType指定的是映射到list集合属性中pojo的类型。

注意说明:

  • 保证SQL的可读性,尽量通俗易懂

  • 根据实际要求,尽量编写性能更高的SQL语句

  • 注意属性名和字段不一致的问题

  • 注意一对多和多对一 中:字段和属性对应的问题

  • 尽量使用Log4j,通过日志来查看自己的错误

十一、动态SQL

什么是动态SQL:动态SQL指的是根据不同的查询条件 , 生成不同的Sql语句。

动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。

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

11.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 NOT NULL COMMENT '浏览量'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

新建实体类

package com.princehan.pojo;

import lombok.Data;

import java.util.Date;

/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/10 22:43
 */
@Data
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;//属性名与字段名不一致
    private int views;
}

编写BlogMapper接口

package com.princehan.dao;

import com.princehan.pojo.Blog;

import java.util.List;
import java.util.Map;

@SuppressWarnings("all")
public interface BlogMapper {
    //插入数据
    int addBlog(Blog blog);
}

编写工具类(用以自动生成id)

package com.gq.util;

import java.util.UUID;

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

编写BlogMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace 绑定一个mapper dao接口-->
<mapper namespace="com.gq.dao.BlogMapper">
    <insert id="addBlog" parameterType="Blog">
        insert into blog(id, title, author, create_time, views)
        values (#{id}, #{title}, #{author}, #{createTime}, #{views})
    </insert>
</mapper>

在mybatis-config.xml里配置

    <settings>
        <!--日志-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!--开启驼峰形式字段匹配-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!--绑定接口-->
    <mappers>
        <!--MapperyuMapper.xml在同一个目录下 可以用类名 可用注解-->
        <mapper class="com.gq.dao.BlogMapper"/>
    </mappers>

编写测试类


import com.gq.dao.BlogMapper;
import com.gq.pojo.Blog;
import com.gq.util.IDUtils;
import com.gq.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.Date;

public class UserDaoTest {


    @Test
    public void testBlog() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Blog blog = new Blog();
        blog.setId(IDUtils.getId());
        blog.setTitle("Mybatis如此简单");
        blog.setAuthor("狂神说");
        blog.setCreateTime(new Date());
        blog.setViews(9999);
        mapper.addBolg(blog);
        blog.setId(IDUtils.getId());
        blog.setTitle("Java如此简单");
        mapper.addBolg(blog);
        blog.setId(IDUtils.getId());
        blog.setTitle("Spring如此简单");
        mapper.addBolg(blog);
        blog.setId(IDUtils.getId());
        blog.setTitle("微服务如此简单");
        mapper.addBolg(blog);
        sqlSession.commit();
        sqlSession.close();
    }
}

在这里插入图片描述

11.2、if语句

需求:根据作者名字和博客名字来查询博客!如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询

新建接口

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

编写映射

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

编写测试类

    @Test
    public void queryBlogIF() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        map.put("title", "Java如此简单");
        map.put("author", "狂神说");
        mapper.queryBlogIF(map);
        sqlSession.close();
    }

在这里插入图片描述
if语句会根据条件真假来添加语句, 如果 author 等于 null,那么查询语句为 select from blog where title=#{title},但是如果title为空呢?那么查询语句为 select from blog where and author=#{author},这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句!

11.3、trim(where、set)

where

修改上面的配置

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

trim

如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>

prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。

set

新建接口

//更新博客
    int updateBlog(Map map);
<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>

这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

来看看与 set 元素等价的自定义 trim 元素吧:

<trim prefix="SET" suffixOverrides=",">
  ...
</trim>

注意,我们覆盖了后缀值设置,并且自定义了前缀值。

@Test
public void updateBlog() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap map = new HashMap();
    map.put("title", "Java如此简单2");
    map.put("author", "狂神说2");
    map.put("id", "8f9b7bd6cee84c49bc08a82e9b07f9df");
    mapper.updateBlog(map);
    sqlSession.close();
}

11.4、choose(when、otherwise)

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

还是上面的例子,但是策略变为:传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回浏览量为 views 的 BLOG。

<select id="queryBlogChoose" parameterType="map" resultType="Blog">
    select * from blog
    <where>
        <choose>
            <when test="title != null">title = #{title}</when>
            <when test="author != null">and author = #{author}</when>
            <otherwise>and views = #{views}</otherwise>
        </choose>
    </where>
</select>
//查询博客
List<Blog> queryBlogChoose(Map map);
@Test
public void queryBlogChoose() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap map = new HashMap();
    map.put("title", "Java如此简单");
    map.put("author", "狂神说");
    map.put("views",9999);
    List<Blog> blogs = mapper.queryBlogChoose(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlSession.close();
}

11.5、sql片段

有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。

  1. 使用sql标签抽取公共的部分
    <sql id="if-title-author">
        <if test="title != null">title = #{title}</if>
        <if test="author != null">and author = #{author}</if>
    </sql>
  1. 引用sql片段
    <select id="queryBlogIF" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <include refid="if-title-author"/>
        </where>
    </select>

注意:

①、最好基于 单表来定义 sql 片段,提高片段的可重用性

②、在 sql 片段中不要包括 where

11.6、foreach

在这里插入图片描述

例子:(id = 1 or id = 2 or id = 3)这样写
在这里插入图片描述

实例:
将数据库中前三个数据的id修改为1,2,3;
需求:我们需要查询 blog 表中 id 分别为1,2,3的博客信息

新建接口

    //查询1-2-3号记录的博客
    List<Blog> queryBlogForeach(Map map);

配置映射

    <!--传递map 存一个集合-->
    <select id="queryBlogForeach" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <foreach collection="ids" item="id" open="and (" separator="or" close=")">
                id = #{id}
            </foreach>
        </where>
    </select>

编写测试类

    @Test
    public void queryBlogForeach() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        ArrayList<Integer> ids = new ArrayList<>();
        for (int i = 1; i <= 3; i++) {
            ids.add(i);
        }
        map.put("ids", ids);
        List<Blog> blogs = mapper.queryBlogForeach(map);
        sqlSession.close();
    }

在这里插入图片描述

小结:其实动态 sql 语句的编写往往就是一个拼接的问题,为了保证拼接准确,我们最好首先要写原生的 sql 语句出来,然后在通过 mybatis 动态sql 对照着改,防止出错。多在实践中使用才是熟练掌握它的技巧

十二、Mybatis缓存(了解)

12.1、简介

什么是缓存 [ Cache ]?

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

为什么使用缓存?

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

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

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

12.2、Mybatis缓存

缓存还是用redis比较好

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

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

    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
    • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。(二级缓存范围更大)
    • 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

12.3、一级缓存

一级缓存也叫本地缓存:

  • 与数据库同一次会话期间查询到的数据会放在本地缓存中。

  • 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库(从同一个sqlsession中执行同样的sql,第二次会直接在一级缓存中拿数据);

  • 一级缓存是SqlSession级别的缓存,是一直开启的,我们关闭不了它;

  • 映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存

手动清理缓存

    @Test
    public void queryUserById() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.queryUserById(1);
        System.out.println(user);
        //手动清理缓存
        sqlSession.clearCache();
        System.out.println("========");
        User user1 = mapper.queryUserById(1);
        System.out.println(user1);
        System.out.println(user == user1);
        sqlSession.close();

    }

12.4、二级缓存

开启二级缓存

<!--显示开启全局缓存 默认开启-->
 <setting name="cacheEnabled" value="true"/>
    <cache/>
    <!--在当前Mapper使用二级缓存-->
    <cache
            eviction="FIFO"
            flushInterval="60000"
            size="512"
            readOnly="true"/>

小结

  • 只要开启了二级缓存,我们在同一个Mapper中的查询,可以在二级缓存中拿到数据
  • 查出的数据都会被默认先放在一级缓存中
  • 只有会话提交或者关闭以后,一级缓存中的数据才会转到二级缓存中

12.5、缓存原理

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值