MyBatis 学习记录

0 阅读24分钟

1、简介

1.1、什么是Mybatis

image.png

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

它支持定制化 SQL、存储过程以及高级映射。

MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。

MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

MyBatis 本是 apache 的一个开源项目 iBatis,2010年这个项目由 apache software foundation 迁移到了 google code,并且改名为 MyBatis 。

2013年11月迁移到 github。

1.2、持久化

数据持久化

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

为什么需要需要持久化?

  • 有一些对象,不能让他丢掉。
  • 内存太贵了

1.3、持久层

Dao层,Service层,Controller层....

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

1.4 为什么需要Mybatis?

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

  • 方便

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

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

  • 优点:

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

2.第一个·Mybatis项目

1 建立数据库

2.准备环境

新建项目

  1. 新建一个普通的maven项目
  2. 删除src目录
  3. 导入maven依赖
<dependencies>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>9.6.0</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>
    <!-- Source: https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.19</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

2.2、创建一个模块

  • 编写mybatis的核心配置文件

image.png

<?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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTime=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/mybatis/example/BlogMapper.xml"/>
    </mappers>
</configuration>
  • 编写mybatis工具类
package com.zhang.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;

public class MybatisUtil {
public static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //第一步:使用mybatis得到SqlSessionFactory
            String resource = "mynatis_config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
         sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}

2.3、编写代码

  • 实体类

image.png

  • Dao接口
package com.zhang.dao;

import com.zhang.pojo.User;

import java.util.List;

public interface UserDao {
    List<User> getUserList();
}
  • 接口实现类

打开你的 UserMapper.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">
<!--        mapper实际相当于JDBC中的UserDaoImpl-->
<!--namespace=绑定一个对应的dao/mapper接口-->
<mapper namespace="com.zhang.dao.UserDao">
    <select id="getUserList" resultType="com.zhang.pojo.User">
        select * from mybatis.user;
    </select>
</mapper>

image.png

关于在maven项目中配置文件资源导出问题

标准的Maven项目都会有一个resources目录来存放我们所有的资源配置文件,但是我们往往在项目中不仅仅会把所有的资源配置文件都放在resources中,同时我们也有可能放在项目中的其他位置,那么默认的maven项目构建编译时就不会把我们其他目录下的资源配置文件导出到target目录中,就会导致我们的资源配置文件读取失败,从而导致我们的项目报错出现异常,比如说尤其我们在使用MyBatis框架时,往往Mapper.xml配置文件都会放在dao包中和dao接口类放在一起的,那么执行程序的时候,其中的xml配置文件就一定会读取失败,不会生成到maven的target目录中,所以我们要在项目的pom.xml文件中进行设置,并且我建议大家,每新建一个maven项目,就把该设置导入pom.xml文件中,以防不测!!!

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

核心配置文件中注册 mappers

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

2.4、测试

注意点:

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

MapperRegistry是什么?

核心配置文件中注册 mappers

<mappers>
    <mapper resource="com/zhang/dao/UserMapper.xml"/>
</mappers>
  • junit测试

image.png

package zhang.dao;

import com.zhang.dao.UserDao;
import com.zhang.pojo.User;
import com.zhang.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class TestU {
    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        //方式一:getMapper
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> all = userDao.getUserList();
        for (User user : all) {
            System.out.println(user);
        }
        //方式二:直接通过select
        List<Object> objects = sqlSession.selectList("com.zhang.dao.UserDao.getUserList");
        for (Object object : objects) {
            System.out.println(object);
        }
        sqlSession.close();

    }
}

你们可以会遇到的问题:

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

3.CRUD

public interface UserMapper {
    List<User> getUserList();
    User getUserById(String id);
    int addUser(User user);
    int updateUser(User user);
    int deleteUser(String id);
}

1、namespace

namespace中的包名要和 Dao/mapper 接口的包名一致!

2、select

选择,查询语句;

  • id:就是对应的namespace中的方法名;
  • resultType:Sql语句执行的返回值!
  • parameterType : 参数类型!
<!--namespace=绑定一个对应的dao/mapper接口-->
<mapper namespace="com.zhang.dao.UserMapper">
    <select id="getUserList" resultType="com.zhang.pojo.User">
        select * from mybatis.user;
    </select>
    <select id="getUserById" resultType="com.zhang.pojo.User" parameterType="int">
        select * from mybatis.user where id=#{id};
    </select>

3、Insert

<!--    对象中的属性可以直接取出来,insert 不需要写 resultType,默认返回:受影响的行数(int)-->
    <insert id="addUser"  parameterType="com.zhang.pojo.User" >
        insert into mybatis.user value (#{id},#{name},#{pwd})
    </insert>
    @Test
    public void test3(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        int rows = userMapper.addUser(new User(4, "zhang", "123"));
        System.out.println(rows);
//        事物需要commit才能生效
        sqlSession.commit();
        sqlSession.close();
    }

4、update

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

5、Delete

<delete id="deleteUser" parameterType="String">
    delete from mybatis.user where id=#{id}
</delete>

6、分析错误

  • 标签不要匹配错
  • resource 绑定mapper,需要使用路径!
  • 程序配置文件必须符合规范!
  • NullPointerException,没有注册到资源!
  • 输出的xml文件中存在中文乱码问题!
  • maven资源没有导出问题!

7、万能Map

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

//万能的Map

int addUser2(Map<String,Object> map);

<insert id="addUser" parameterType="map">

insert into mybatis.user (id, pwd) values (#{id},#{name},#{pwd});

</insert>

用 Map 传参,想传几个字段就传几个字段,不需要创建完整的 User 对象!可以只传 id、只传 password,也可以都传,超级灵活

    @Test
    public void test6(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", "zhangsan");
        map.put("id", 5);
        int i = userMapper.addUser2(map);
        System.out.println(i);
        sqlSession.commit();
        sqlSession.close();
    }
}

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

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

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

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

8、思考题

模糊查询怎么写?

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

    List userList = mapper.getUserLike("%李%");

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

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

4、配置解析

1、核心配置文件

  • mybatis-config.xml
  • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。
   configuration(配置)

properties(属性)

settings(设置)

typeAliases(类型别名)

typeHandlers(类型处理器)

objectFactory(对象工厂)

plugins(插件)

environments(环境配置)

environment(环境变量)

transactionManager(事务管理器)

dataSource(数据源)

databaseIdProvider(数据库厂商标识)

mappers(映射器) 

2、环境配置(environments)

image.png MyBatis 可以配置成适应多种环境

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

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

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

3、属性(properties)

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

这些属性都是可外部配置且可动态替换的,既可以在典型的 Java 属性文件中配置,亦可通过 properties

元素的子元素来传递。【db.properties】

driver=com.mysql.jdbc.Driver
username=root
password=123456
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=ture&characterEncoding=utf-8&serverTime=GMT

image.png

image.png

4、类型别名(typeAliases)

  • 类型别名是为 Java 类型设置一个短的名字。
  • 存在的意义仅在于用来减少类完全限定名的冗余。
    <typeAliases>
<!--        为实体类添加别名-->
        <typeAlias type="com.zhang.pojo.User" alias="user"/>
    </typeAliases>

image.png

  • Mapper 接口 不能设置别名

  • namespace 必须写全类名

  • 别名只给 实体类

也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:user或者User也可以

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

image.png 注解别名权重 > 手动指定别名(typeAlias) > 包扫描自动别名

    import org.apache.ibatis.type.Alias;
    @Alias("myUser") // 注解别名 
    public class User { // ...
    
    }

5、设置(settings)

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

image.png

image.png

image.png

6、其他配置

  • typeHandlers(类型处理器)

  • objectFactory(对象工厂)

  • plugins插件

    • mybatis-generator-core

    • mybatis-plus

    • 通用mapper

7、映射器(mappers)

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

方式一:

<mappers>

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

</mappers>

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

<mappers>

<mapper class="com.kuang.dao.UserMapper"/>

</mappers>

注意点:

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

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

<!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册! -->
<mappers>
    <package name="com.kuang.dao"/>
</mappers>

注意点:

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

8、生命周期和作用域

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

SqlSessionFactoryBuilder:

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

image.png SqlSessionFactory:

  • 说白了就是可以想象为:数据库连接池

  • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。

  • 因此 SqlSessionFactory 的最佳作用域是应用作用域。

  • 最简单的就是使用单例模式或者静态单例模式。

SqlSession:

  • 连接到连接池的一个请求!

  • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。

  • 用完之后需要赶紧关闭,否则资源被占用!

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

1.问题

image.png 解决方法:

  • 起别名
<select id="getUserById" resultType="com.kuang.pojo.User">
    select id,name,pwd as password from mybatis.user where id = #{id}
</select>

2、resultMap

结果集映射

    id    name    pwd

    id    name    password
<mapper namespace="com.zhang.dao.UserMapper">
    <resultMap id="userMap" type="User">
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="pwd" property="password"/>
    </resultMap>
    <select id="getUserList" resultMap="userMap">
        select * from mybatis.user;
    </select>

● resultMap 元素是 MyBatis 中最重要最强大的元素

● resultMap 的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。

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

● 如果世界总是这么简单就好了。

6、日志

6.1、日志工厂

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

曾经:sout、debug

现在:日志工厂!

logImpl

  • SLF4J
  • LOG4J 【掌握】
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING 【掌握】
  • NO_LOGGING

在Mybatis中具体使用那个一日志实现,在设置中设定!

STDOUT_LOGGING 标准日志输出 这个类型不需要导包直接用

image.png

image.png

6.2、Log4j

什么是Log4j?

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

1.先导入log4j的包

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

2.log4j.properties

  • 放在resource包下
# 将等级为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/kuang.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{yy-MM-dd}][%c]%m%n

# 日志输出级别

log4j.logger.org.mybatis=DEBUG

log4j.logger.java.sql=DEBUG

log4j.logger.java.sql.Statement=DEBUG

log4j.logger.java.sql.ResultSet=DEBUG

log4j.logger.java.sql.PreparedStatement=DEBUG
  1. 配置log4j为日志的实现
<settings>
    <setting name="logImpl" value="LOG4J"/>
</settings>
  1. Log4j的使用!,直接测试运行刚才的查询

log4j2

Log4j 1.x = 2015 年死亡 + 永久不补漏洞 + 架构过时 + 类不兼容 = 完全淘汰 现在更适合的是log4j2

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

log4j2配置文件log4j2.xml,放在resource下

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" encoding="UTF-8">
    <!-- 控制台输出 -->
    <Appenders>
<!--        输出格式配置,文件和控制台-->
        <Console name="Console" target="SYSTEM_OUT">
            <!-- 日志格式:时间 + 线程 + 级别 + 类名 + 信息 -->
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{50} - %msg%n" charset="UTF-8"/>
        </Console>
        <File name="LogFile" fileName="logs/app.log" append="true">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{50} - %msg%n"/>
        </File>
    </Appenders>

    <!-- 日志规则 -->
    <Loggers>
        <!-- 根日志:默认输出 info 级别 -->
        <Root level="info">
<!--            输出到控制台-->
            <AppenderRef ref="Console"/>
<!--            输出到文件-->
            <AppenderRef ref="LogFile"/>
        </Root>

        <!-- ===================== 关键:打印 MyBatis SQL ===================== -->
        <!-- 把 com.zhang.dao 改成你自己的 Mapper 接口包名!!! -->
        <Logger name="com.zhang.mapper" level="debug" additivity="false">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="LogFile"/>
        </Logger>
        <Logger name="test" level="info" additivity="false">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="LogFile"/>
        </Logger>
        <!-- MyBatis 自身日志 -->
        <Logger name="org.apache.ibatis" level="info"/>
    </Loggers>
</Configuration>

依赖

<!-- Source: https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.25.3</version>
    <scope>compile</scope>
</dependency>

运行日志如下

image.png 简单使用

  1. 在要使用Log4j 的类中,导入包 import org.apache.logging.log4j.LogManager;

    import org.apache.logging.log4j.Logger;

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

    static Logger logger = LogManager.getLogger(Test01.class);

  3. 日志级别

    logger.info("info:进入了testLog4j");

    logger.debug("debug:进入了testLog4j");

    logger.error("error:进入了testLog4j");

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(当前类.class);
import com.zhang.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Test01 {
    static Logger logger = LogManager.getLogger(Test01.class);
    @Test
    public void test01(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        logger.info("测试==========");
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> all = mapper.findAll();
        for (User user : all) {
            System.out.println(user);
        }
        sqlSession.close();
    }
}

image.png

  • 也有说法统一用 SLF4J 接口,据说是行业标准写法,可以减少耦合
    import org.slf4j.Logger; 
    import org.slf4j.LoggerFactory; 
    private static final Logger logger = LoggerFactory.getLogger(Test01.class);

需要如下依赖

    <!-- SLF4J 接口(必须) -->
    <dependency> 
        <groupId>org.slf4j</groupId> 
        <artifactId>slf4j-api</artifactId>
        <version>2.0.9</version> 
    </dependency>
    <!-- Log4j2 核心(真正打日志) --> 
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.25.3</version> 
    </dependency>
    <dependency> 
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.25.3</version> 
    </dependency>
    <!-- 桥接:让 SLF4J 用 Log4j2 输出(必须!) --> 
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j2-impl</artifactId>
        <version>2.25.3</version> <scope>runtime</scope> 
    </dependency>
  • SLF4J = 接口(不干活,只定义怎么调用)

  • Log4j2 = 实现(真正输出日志到控制台 / 文件)

  • 企业必须用 SLF4J + Log4j2/Logback,不能直接用 Log4j2 原生 Logger

7、分页

7.1 Limit分页

思考:为什么要分页?

  • 减少数据的处理量

语法:

    SELECT * from user limit startIndex,pageSize;
    SELECT * from user limit 3; # [0,n]

使用Mybatis实现分页,核心SQL

  1. 接口
    //分页

    List<User> getUserByLimit(Map<String,Integer> map);
  1. Mapper.xml
<select id="findByLimit" parameterType="map" resultType="user">
    select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
  1. 测试
public void test02(){
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    HashMap<String, Object> map = new HashMap<>();
    map.put("startIndex", 0);
    map.put("pageSize", 2);
    List<User> users = mapper.findByLimit(map);
    for (User user : users) {
        System.out.println(user);
    }
    sqlSession.close();
}

image.png

7.2、RowBounds分页

不再使用SQL实现分页

  1. 接口
      //分页2

    List<User> getUserByRowBounds();
  1. mapper.xml
    <select id="getUserByRowBounds" resultMap="UserMap">

    select * from mybatis.user

    </select>
  1. 测试
@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();}

7.3、分页插件

image.png pagehelper.github.io/

8、使用注解开发

8.1、面向接口编程

  • 大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程
  • 根本原因:==解耦==,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好
  • 在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;
  • 而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。

关于接口的理解

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

8.2、使用注解开发

  1. 注解在接口上实现
public interface UserMapper {
    @Select("select * from mybatis.user")
     List<User> findAll();
    @Select("select * from mybatis.user where id=#{id}")
    User findById(int id);
}
  1. 需要在核心配置文件中绑定接口!
<mappers>
    <mapper class="com.zhang.dao.UserMapper"/>
</mappers>
  1. 测试

image.png

8.3、CRUD

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

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

编写接口

public interface UserMapper {
    @Select("select * from mybatis.user")
     List<User> findAll();
    @Select("select * from mybatis.user where id=#{id}")
    User findById(int id);
    @Insert("insert into mybatis.user values (#{id},#{name},#{pwd})")
    int InsertUser(User user);
    @Delete("DELETE from mybatis.user where id=#{id}")
    int DeleteById(@Param("id") int userId);//@Param在有多个基本类型参数时使用,把“id”绑定到后面的形参
    @Update("update mybatis.user set id=#{id},name=#{name},pwd=#{pwd} where id=#{id}")
    int UpdateUser(User user);

}

测试类

package com.zhang.dao;

import com.zhang.pojo.User;
import com.zhang.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class Test1 {
    @Test
    public void test01(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> all = mapper.findAll();
        for (User user : all) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    @Test
    public void test02(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User byId = mapper.findById(1);
        System.out.println(byId);
        sqlSession.close();
    }
    @Test
    public void test03(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int i = mapper.InsertUser(new User(6, "test", "6666"));
        System.out.println(i);
//        把工具类的得到SqlSession的方法改为
//        return sqlSessionFactory.openSession(ture);
//        即可实现自动提交
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void test04(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int i = mapper.DeleteById(6);
        System.out.println(i);
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void test05(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int i = mapper.UpdateUser(new User(5, "zhanglei", "123456"));
        System.out.println(i);
        sqlSession.commit();
        sqlSession.close();
    }
}

关于@Param()注解

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

9、Lombok

Lombok 是一个 Java 库,通过注解自动生成 Java 类里的样板代码(getter、setter、构造器、toString 等),让代码更简洁、不用手写重复内容。

使用步骤:

  1. 在IDEA中安装Lombok插件!

image.png

  1. 在项目中导入lombok的jar包
<!-- Source: https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.42</version>
    <scope>compile</scope>
</dependency>

image.png

  • Lombok 需要开启「注解处理器」,否则 IDEA 不识别自动生成的 getter/setter

image.png

  • Lombok 的 @Data 不自带全参构造 如果要全参加注解 @AllArgsConstructor , 但加了这个注解无参就没了 , 所以我们的最佳实践为
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}

更具有可读性更方便的插件

image.png

10、一对多查询

测试环境搭建

image.png

image.png

按照查询嵌套处理

<?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.zhang.mapper.StudentMapper">
    <resultMap id="studentTeacher" type="student">
        <!-- 
            当实体类里的字段不是普通类型(int/String),而是另一个对象(比如 Teacher)时,
            不能用普通 result,要用 association 标签处理“关联对象”。
        
            column="tid"     表示:从学生表里拿 tid 这个字段的值
            javaType="Teacher" 表示:这个字段最终要封装成 Teacher 对象
            select="getTeacher" 表示:拿上面的 tid 去调用 getTeacher 这条 SQL,
                                      把查到的老师数据塞给 student 里的 teacher 对象
        -->
        <association property="teacher" column="tid" javaType="teacher" select="getTeacher"/>
    </resultMap>
    <select id="selectAll" resultMap="studentTeacher">
        select * from mybatis.student;
    </select>
    <select id="getTeacher" resultType="teacher" >
        select * from mybatis.teacher where id=#{tid}
    </select>
</mapper>

image.png

按照结果嵌套处理

 <select id="selectAll2" resultMap="studentTeacher2">
        select s.id id,s.name name,t.name tname,t.id tid
        from mybatis.student s,mybatis.teacher t
        where s.tid=t.id
    </select>
<!--    多表联查 + 自定义别名必须自己指定全部字段-->
    <resultMap id="studentTeacher2" type="student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
<!--        相当于把student的对象字段teacher看作和student一个水平,
               把sql语句里的字段映射到teacher里去
               现在column="tid"已经没有任何作用,因为结果和表里的tid字段没有任何关系,可以不写-->
        <association property="teacher" column="tid" javaType="teacher">
            <result property="id" column="tid"/>
            <result property="name" column="tname" />
        </association>
    </resultMap>

image.png

11、一对多处理

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

对于老师而言,就是一对多的关系!

image.png

按照结果嵌套处理

<?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.zhang.dao.TeacherMapper">
   <select id="getTeacherById" resultMap="teacherStudent">
      select t.id teacherId ,t.name tname,s.id sid,s.name sname
      from mybatis.student s,mybatis.teacher t
      where s.tid=t.id and t.id=#{id}
   </select>
   <resultMap id="teacherStudent" type="teacher">
      <result property="id" column="teacherId"/>
      <result property="name" column="tname"/>
<!--       处理集合字段用collection,
      因为 students 是 List 集合,MyBatis 不知道集合里装的是什么类型,需要实现集合中的映射
      所以必须用 ofType 指定里面的元素类型是 Student。-->
      <collection property="students" ofType="student">
         <result property="id" column="sid"/>
         <result property="name" column="sname"/>
         <result property="tid" column="teacherId"/>
      </collection>
   </resultMap>
</mapper>

column 映射的永远是:查询结果集里的列名,不是数据库表里的字段!

image.png

按照查询嵌套处理

    <!-- 第一步:查老师 --> 
    <select id="getTeacherById2" resultMap="teacherStudent2">
        select * from mybatis.teacher where id=#{id} 
    </select> 
    <!-- 第二步:映射老师,告诉MyBatis学生怎么来 -->
    <resultMap id="teacherStudent2" type="teacher"> 
        <collection property="students" 
                    javaType="List" <!-- 用List装学生 --> 
                    ofType="student" <!-- 装Student -->
                    select="getStudents" <!-- 调用子查询拿学生 -->
                    column="id" <!-- 把老师id传给子查询 -->
        /> 
    </resultMap> 
    <!-- 第三步:子查询 → 查询该老师的所有学生 -->
    <select id="getStudents" resultType="student"> 
        select * from mybatis.student where tid=#{id} 
    </select>

只要 association /collection 里写了 select=

column 就瞬间变成:传递参数的作用!

不再是映射字段!

  • 只要你在 里写了任何东西(哪怕只写了一个 collection)MyBatis 就会关闭自动映射,只认你手动写的字段!

image.png

小结

  1. 关联 - association 【多对一】

  2. 集合 - collection 【一对多】

  3. javaType & ofType

    • JavaType 用来指定实体类中属性的类型
    • ofType 用来指定映射到List或者集合中的 pojo类型,泛型中的约束类型!

注意点:

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

12、动态 SQL

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

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

 动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。
    在 MyBatis 之前的版本中,有很多元素需要花时间了解。
    MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。
    MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。

 if

 choose (when, otherwise)

 trim (where, set)

foreach  

环境搭建

数据库下划线命名 create_time 与 Java 驼峰命名 createTime 不匹配的经典问题

image.pngmybatis-config.xml 中添加配置:

<settings>
    <!-- 开启下划线转驼峰自动映射 -->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

MyBatis 核心配置文件 标签顺序不能乱!

正确顺序必须是:

  1. properties (数据库配置文件)
  2. settings (驼峰、日志等设置)
  3. typeAliases (别名)
  4. 其他...
  5. environments (环境、数据源)
  6. mappers (映射器)

UUID获取唯一ID

package com.zhang.util;

import java.util.UUID;

public class IDUtil {
    public static String getID() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
public class MyTest {
    @Test
    public void test() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Blog blog = new Blog();
        blog.setId(IDUtil.getID());
        blog.setTitle("Mybatis如此简单");
        blog.setAuthor("狂神说");
        blog.setCreateTime(new Date());
        blog.setViews(9999);

        mapper.Insert(blog);

        blog.setId(IDUtil.getID());
        blog.setTitle("Java如此简单");
        mapper.Insert(blog);

        blog.setId(IDUtil.getID());
        blog.setTitle("Spring如此简单");
        mapper.Insert(blog);

        blog.setId(IDUtil.getID());
        blog.setTitle("微服务如此简单");
        mapper.Insert(blog);
        sqlSession.commit();
        sqlSession.close();

    }
}

if语句标签

当想实现一个需求:依据输入的内容查找博客 比如没有输入任何数据时,输出全部的博客, 输入作者字段只输出该作者的字段等

public interface BlogMapper {
    int Insert(Blog blog);
    List<Blog> selectAllIf(Map<String, Object> map);
}
<mapper namespace="com.zhang.dao.BlogMapper">
    <insert id="Insert" >
        insert into mybatis.blog values (#{id},#{title},#{author},#{createTime},#{views})
    </insert>
    <select id="selectAllIf" resultType="Blog">
        select * from mybatis.blog
        where 1=1
#           一个if语句表示如果满足test条件直接在语句后面拼接sql
        <if test="id!=null">
            and id=#{id}
        </if>
        <if test="title!=null">
            and title=#{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
        <if test="createTime!=null">
            and createTime=#{createTime}
        </if>
        <if test="views!=null">
            and views=#{views}
        </if>
    </select>

image.png

image.png

在上面这个例子里,我用了1=1来防止出现where后面直接跟上and的错误,

     where 1=1 and id=1        where and id=1(报错)

这显然不合规范,这时我们可以用where标签改造

<select id="selectAllIf" resultType="Blog">
       select * from mybatis.blog
       <where>
<!-- 这里要用xml注释而不是#        一个if语句表示如果满足test条件直接在语句后面拼接sql -->
       <if test="id!=null">
           and id=#{id}
       </if>
       <if test="title!=null">
           and title=#{title}
       </if>
       <if test="author!=null">
           and author=#{author}
       </if>
       <if test="createTime!=null">
           and createTime=#{createTime}
       </if>
       <if test="views!=null">
           and views=#{views}
       </if>
       </where>
   </select>

<where> 标签的魔力:

  • 自动去掉最前面多余的 and
  • 没有任何条件时,自动去掉 where 关键字
  • 你完全不用操心语法问题

choose (when, otherwise)

choose = Java 里的 switch case /if...else if...else

意思:多选一,只执行满足条件的第一个,其他全部不执行!

    <select id="selectAllChoose" resultType="Blog">
        select * from mybatis.blog
        <where>
<!--            类似与swich 语句,只选一个when进入,没有符合的进入otherwise-->
            <choose>
                <when test="id!=null">
                    id=#{id}
                </when>
                <when test="title!=null">
                    and title=#{title}
                </when>
                 <when test="author!=null">
                     author=#{author}
                  </when>
                <otherwise>
                    views>0
                 </otherwise>
            </choose>
        </where>
    </select>

image.png

trim (where,set)

传统的使用update方法

<update id="update" >
    update mybatis.blog set id=#{id}
    ,title=#{title}
    ,author=#{author}
    ,create_time =#{createTime}
    ,views =#{views}
    where id=#{id}
</update>
@Test
public void test4() {
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap<String, Object> map = new HashMap<>();
    map.put("id","12fa04baa9f24c7eaf185d194315a9c7");
    map.put("title","JavaTest");
    map.put("author","<UNK>");
    map.put("createTime",new Date());
    map.put("views",9999);
    int update = mapper.update(map);
    System.out.println(update);
    sqlSession.commit();
    sqlSession.close();
}

Set标签

  • 自动在前面加 SET

  • 自动去掉最后面多余的逗号

  • 非常适合动态更新字段

   <update id="update" >
        update mybatis.blog
        <set>
            <if test="id!=null">
              id=#{id},
            </if>
            <if test="title!=null">
                title=#{title},
            </if>
            <if test="author!=null">
               author=#{author},
            </if>
            <if test="createTime!=null">
            <!--   在开启驼峰命名(mapUnderscoreToCamelCase)
只对【查询结果封装】有效!对【SQL 语句本身】无效!
                    SQL 语句里,等号左边永远写数据库字段名-->
                create_time=#{createTime},
            </if>
            <if test="views!=null">
                views=#{views},
            </if>
        </set>
        where id=#{id}
    </update>

image.png

trim 是什么?

    <trim 
          prefix="前面加什么" 
          suffix="后面加什么" 
          prefixOverrides="前面要删掉什么" 
          suffixOverrides="后面要删掉什么"  
      >
例子 1:trim 实现 where(最经典)
<trim prefix="WHERE" prefixOverrides="AND |OR ">
    <if test="title != null"> and title = #{title} </if>
    <if test="author != null"> and author = #{author} </if>
</trim>

它做了什么?

  1. prefix="WHERE" → 前面自动加 WHERE
  2. prefixOverrides="AND" → 如果开头是 AND,自动删掉
例子 2:trim 实现 set(更新用)
<trim prefix="SET" suffixOverrides=",">
    <if test="title != null"> title = #{title}, </if>
    <if test="author != null"> author = #{author}, </if>
</trim>

它做了什么?

  1. prefix="SET" → 前面加 SET
  2. suffixOverrides="," → 删掉最后多余的逗号

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

SQL标签

  • <sql 标签可以提取一段常用sql,然后用include标签引用到任何语句
   <sql id="if-all">
        <if test="id!=null">
            and id=#{id}
        </if>
        <if test="title!=null">
            and title=#{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
        <if test="createTime!=null">
            and createTime=#{createTime}
        </if>
        <if test="views!=null">
            and views=#{views}
        </if>
    </sql>
    <select id="selectAllIf" resultType="Blog">
        select * from mybatis.blog
        <where>
<!-- 这里要用xml注释而不是#        一个if语句表示如果满足test条件直接在语句后面拼接sql -->
        <include refid="if-all"></include>
        </where>
    </select>

image.png

注意事项:

  • 最好基于单表来定义SQL片段!
  • 不要存在where标签

foreach标签

    <foreach 
             collection="ids"  <!-- 你传进来的集合/数组名字 --> 
            item="id"  <!-- 每次遍历出来的元素叫 id --> 
            open="id in ("   <!-- 循环开始前拼接:id in ( -->
            separator=","   <!-- 元素之间用逗号分隔 -->
            close=")"   <!-- 循环结束后拼接 ) --> 
    >

例子: 查找id为1,2,3的博客

 select * from blog where id in (1,2,3)
<select id="selectByForEach" resultType="blog">
    <!-- select * from blog where id in (1,2,3)-->
    select * from mybatis.blog
                 <where>
                     <foreach collection="ids"
                              index="index"
                              item="id"
                              open="id in ("
                              separator=","
                              close=")">
                         #{id}
                     </foreach>
                 </where>
</select>

需要一个id集合,于是我们传入一个id集合

@Test
public void test5() {
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap<String, Object> map = new HashMap<>();
    ArrayList<Integer> ids = new ArrayList<Integer>(){
        {
            add(1);
            add(2);
            add(3);
        }
    };
    map.put("ids",ids);
    List<Blog> blogs = mapper.selectByForEach(map);
    blogs.forEach(System.out::println);
   sqlSession.close();
}

13、缓存

  1. 什么是缓存 [ Cache ]?

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

    • 减少和数据库的交互次数,减少系统开销,提高系统效率。
  3. 什么样的数据能使用缓存?

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

13.2、Mybatis缓存

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

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

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

13.3、一级缓存

  • 一级缓存也叫本地缓存: SqlSession

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

测试步骤:

  1. 开启日志!
  2. 测试在一个Sesion中查询两次相同记录
  3. 查看日志输出
    • 可以看到两次查询实际执行了一次

image.png 缓存失效的情况:

  1. 查询不同的东西
  2. 增删改操作,可能会改变原来的数据,所以必定会刷新缓存!

image.png

  1. 查询不同的Mapper.xml
  2. 手动清理缓存!
  • 小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!

一级缓存就是一个Map。

image.png

13.4、二级缓存

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

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

  • 工作机制

    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
    • 新的会话查询信息,就可以从二级缓存中获取内容;
    • 不同的mapper查出的数据会放在自己对应的缓存(map)中; 步骤:
  1. 开启全局缓存
     <setting name="cacheEnabled" value="true"/>   
  1. 在要使用二级缓存的Mapper中开启
    <cache/>

也可以自定义参数

    <cache eviction="FIFO"

    flushInterval="60000"

    size="512"

    readonly="true"/> 
  1. 测试

问题:我们需要将实体类序列化!否则就会报错!

Caused by: java.io.NotSerializableException: com.kuang.pojo.User

小结:

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