mybatis

mybatis 是一款优秀的半自动的orm持久层框架,它支持自定义 sql、存储过程以及高级映射。

mybatis 免除了几乎所有的 jdbc 代码以及设置参数和获取结果集的工作。

mybatis 可以通过简单的 xml 或注解来配置和映射原始类型、接口和 java pojo(plain old java objects,普通老式 java 对象)为数据库中的记录。

持久层:可以立即保存在磁盘上,在这里可以理解为与数据库相关操作。

  1. 什么是orm

    object relation mapping 对象关系映射

    对象指的是面向面向对象,关系指的是数据库中的表,

    例如java语言中的pojo类与数据库模型之间的对应关系。

    orm
    orm
    orm

  2. 为什么mybatis是半自动orm框架

    public class user(){
        private long id;
        private string realname;
    }
    
    user user = user .getbyid(3);
    
    select `id`,`realname` from `user` where `id` = 3;
    

    以上用例为orm框架部分执行代码,发现在orm框架中不需要使用sql语句,

    大大减少了程序员学习成本和sql语句维护成本,

    另外当数据库产品更换的之后无需重新编写项目中的sql语句

    -- mysql
    select * from `user` limit 10;
    -- sqlserver
    select * from `user` top 10;
    

    用mybatis进行开发的,需要手写sql语句,而orm框架例如hibernate则不需要编写sql语句。

  3. 为什么mybais是半自动orm框架我们还要去学习呢

    因为mybatis使用自定义sql所以更加灵活尤其在多表操作

mybaits工作原理

jdbc核心对象

  1. drivermanager,数据库驱动管理对象
  2. connection,数据库连接对象
  3. statement | preparestatement ,操作数据库sql语句对象
  4. resultset,结果集对象

mybaits核心对象

  1. sqlsession对象,该对象包含了执行sql语句的所有方法,例如jdbc里面connection

    对象说明
    executor接口执行器.统一调度其他三个对象执行对应的sql
    statementhandler使用的数据库中的statement执行操作 相当于字符串拼接
    preparestatement使用sql传参的方式处理
    resulthandler对最后的结果进行封装
  2. executor接口,将传递过来的参数动态生成sql语句,负责查询缓存。

  3. mappedstatement对象,该对象负责对sql封装,用于存储需要映射的sql语句及参数等信息

  4. resulthandler对象,用户返回结果集合,封装成最红想要的数据类型,可以自定义返回类型

mybatis执行流程

mybatis执行流程

快速上门

新建maven项目并导入相关依赖

mvn archetype:generate

<project xmlns="http://maven.apache.org/pom/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
         xsi:schemalocation="http://maven.apache.org/pom/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelversion>4.0.0modelversion>
  <groupid>com.lihaozhegroupid>
  <artifactid>mybatisartifactid>
  <version>1.0-snapshotversion>
  <name>mybatisname>
  <packaging>jarpackaging>
  <properties>
    <jdk.version>17jdk.version>
    <maven.compiler.source>17maven.compiler.source>
    <maven.compiler.target>17maven.compiler.target>
    <maven.compiler.compilerversion>17maven.compiler.compilerversion>
    <maven.compiler.encoding>utf-8maven.compiler.encoding>
    <project.build.sourceencoding>utf-8project.build.sourceencoding>
    <project.reporting.outputencoding>utf-8project.reporting.outputencoding>
    <maven.test.failure.ignore>truemaven.test.failure.ignore>
    <maven.test.skip>truemaven.test.skip>
    <junit.version>5.8.2junit.version>
    <fastjson.version>2.0.6fastjson.version>
    <gson.version>2.9.0gson.version>
    <hutool.version>5.8.0.m3hutool.version>
    <jackson.version>2.13.3jackson.version>
    <lombok.version>1.18.24lombok.version>
    <java-testdata.version>1.1.2java-testdata.version>
  properties>
  <dependencies>
    <dependency>
      <groupid>org.junit.jupitergroupid>
      <artifactid>junit-jupiter-apiartifactid>
      <version>${junit.version}version>
      <scope>testscope>
    dependency>
    <dependency>
      <groupid>com.github.binarywanggroupid>
      <artifactid>java-testdata-generatorartifactid>
      <version>${java-testdata.version}version>
    dependency>
    
    
    <dependency>
      <groupid>org.apache.commonsgroupid>
      <artifactid>commons-lang3artifactid>
      <version>3.8.1version>
    dependency>
    
    <dependency>
      <groupid>commons-iogroupid>
      <artifactid>commons-ioartifactid>
      <version>2.11.0version>
    dependency>
    <dependency>
      <groupid>org.junit.jupitergroupid>
      <artifactid>junit-jupiter-engineartifactid>
      <version>${junit.version}version>
      <scope>testscope>
    dependency>
    <dependency>
      <groupid>cn.hutoolgroupid>
      <artifactid>hutool-allartifactid>
      <version>${hutool.version}version>
    dependency>
    <dependency>
      <groupid>org.projectlombokgroupid>
      <artifactid>lombokartifactid>
      <version>${lombok.version}version>
      <scope>providedscope>
    dependency>
    
    
    <dependency>
      <groupid>com.alibabagroupid>
      <artifactid>fastjsonartifactid>
      <version>${fastjson.version}version>
    dependency>
    
    <dependency>
      <groupid>com.google.code.gsongroupid>
      <artifactid>gsonartifactid>
      <version>${gson.version}version>
    dependency>
    
    <dependency>
      <groupid>com.fasterxml.jackson.coregroupid>
      <artifactid>jackson-coreartifactid>
      <version>${jackson.version}version>
    dependency>
    <dependency>
      <groupid>com.fasterxml.jackson.coregroupid>
      <artifactid>jackson-annotationsartifactid>
      <version>${jackson.version}version>
    dependency>
    <dependency>
      <groupid>com.fasterxml.jackson.coregroupid>
      <artifactid>jackson-databindartifactid>
      <version>${jackson.version}version>
    dependency>
    <dependency>
      <groupid>com.fasterxml.jackson.datatypegroupid>
      <artifactid>jackson-datatype-jsr310artifactid>
      <version>${jackson.version}version>
    dependency>
    <dependency>
      <groupid>mysqlgroupid>
      <artifactid>mysql-connector-javaartifactid>
      <version>8.0.29version>
    dependency>
    <dependency>
      <groupid>org.mybatisgroupid>
      <artifactid>mybatisartifactid>
      <version>3.5.10version>
    dependency>
    <dependency>
      <groupid>com.alibabagroupid>
      <artifactid>druidartifactid>
      <version>1.2.8version>
    dependency>
    <dependency>
      <groupid>org.springframeworkgroupid>
      <artifactid>spring-contextartifactid>
      <version>5.3.20version>
    dependency>
    <dependency>
      <groupid>org.slf4jgroupid>
      <artifactid>slf4j-simpleartifactid>
      <version>1.7.36version>
    dependency>
  dependencies>
  <build>
    
    
    <plugins>
      <plugin>
        <groupid>org.apache.maven.pluginsgroupid>
        <artifactid>maven-war-pluginartifactid>
        <version>3.3.2version>
      plugin>
      
      <plugin>
        <groupid>org.apache.maven.pluginsgroupid>
        <artifactid>maven-compiler-pluginartifactid>
        <version>3.8.1version>
        <configuration>
          
          <encoding>utf-8encoding>
          
          <source>${jdk.version}source>
          <target>${jdk.version}target>
        configuration>
      plugin>
      <plugin>
        <groupid>org.apache.maven.pluginsgroupid>
        <artifactid>maven-clean-pluginartifactid>
        <version>3.2.0version>
      plugin>
      <plugin>
        <groupid>org.apache.maven.pluginsgroupid>
        <artifactid>maven-resources-pluginartifactid>
        <version>3.2.0version>
      plugin>
      
      <plugin>
        <groupid>org.apache.maven.pluginsgroupid>
        <artifactid>maven-surefire-pluginartifactid>
        <version>2.22.2version>
        <configuration>
          <skip>trueskip>
        configuration>
      plugin>
    plugins>
  build>
project>

根据数据表生成对应pojo类

idea

编写数据源文件

src/main/resources/config.properties

driver=com.mysql.cj.jdbc.driver
url=jdbc:mysql:///mybatis?useunicode=true&characterencoding=utf8&usessl=false&useserverprepstmts=false&rewritebatchedstatements=true&cacheprepstmts=true&allowmultiqueries=true&servertimezone=aisa/shanghai
username=root
password=123456

编写核心配置文件

src/main/resources/mybatis/mybatis-config.xml


doctype configuration
        public "-//mybatis.org//dtd config 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <properties resource="config.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>
    
configuration>

mybatis核心配置文件

测试数据库连通性

@test
public void testconetion() throws ioexception {
    // 核心配置文件classpath路径
    string resource = "mybatis/mybatis-config.xml";
    // 加载配置文件
    reader reader = resources.getresourceasreader(resource);
    // 构建会话工厂
    sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
    // 从sqlsessionfactory对象中获取sqlsession
    sqlsession sqlsession = sqlsessionfactory.opensession();
    system.out.println(sqlsession.getconnection());
    // 归还连接给数据源
    sqlsession.close();
}

编写接口

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/6 上午8:52
 */
public interface personmapper {
    /**
     * 查询用户列表 resulttype
     *
     * @return
     */
    list<person> selectall4t();
}

编写映射配置文件

src/main/java/com/lihaozhe/mapper/personmapper.xml

或者

src/main/resources/com/lihaozhe/mapper/personmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.personmapper">
    
    
    <select id="selectall4t" resulttype="com.lihaozhe.pojo.person">
        select *
        from `person`
    select>
mapper>

mybatis映射配置文件

核心配置文件加载映射配置文件


<mappers>
    
    
    
    
    
    
    
    <package name="com.lihaozhe.mapper"/>
mappers>

完整核心配置文件


doctype configuration
        public "-//mybatis.org//dtd config 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <properties resource="config.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>
        
        
        
        
        
        
        
        <package name="com.lihaozhe.mapper"/>
    mappers>
configuration>

测试

src/test/java/com/lihaozhe/mapper/personmappertest.java

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/6 上午8:52
 */
public class personmappertest {
    private sqlsession sqlsession;
    // junit5 @beforeall和@beforeeach注解替换了 junit4 中的@before注解。
    // 它⽤于表⽰应在当前类中的每个@test⽅法之前执⾏注解⽅法。
    // 注意:@beforeall注解的⽅法必须为静态⽅法,否则它将引发运⾏时错误。
    // 注意:@beforeeach注解的⽅法不得为静态⽅法,否则它将引发运⾏时错误。
    @beforeeach
    public void opensqlsession() throws ioexception {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = resources.getresourceasreader(resource);
        // 构建会话工厂
        sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        // 从sqlsessionfactory对象中获取sqlsession
        sqlsession = sqlsessionfactory.opensession();
    }
    @test
    public void selectall4t() {
        // 获取该接口的代理对象
        personmapper mapper = sqlsession.getmapper(personmapper.class);
        // 执行接口中的方法
        list<person> people = mapper.selectall4t();
        // 释放sqlsession资源
        sqlsession.close();
        // 遍历集合
        people.foreach(system.out::println);
    }
}

测试结果发现 idcard属性获取到的结果为null,

这是由于查询字段中没有idcard字段,

换言之 idcard属性 没有与 id_card字段形成映射关系

解决方法有两种:

  1. 使用resultmap做结果集映射
  2. 在核心配置文件中设置 mapunderscoretocamelcase 值为 true

解决驼峰命名与下划线映射关系

使用 resultmap

映射配置文件中编写 resultmap


<resultmap id="personmap" type="com.lihaozhe.pojo.person">
    
    <id property="id" column="id"/>
    <result property="id" column="id"/>
    <result property="uuid" column="uuid"/>
    <result property="mobile" column="mobile"/>
    <result property="nickname" column="nickname"/>
    <result property="idcard" column="id_card"/>
resultmap>

修改select id=“selectall4m” 的属性 resulttype=“com.lihaozhe.pojo.person” 为 resultmap=“personmap”

<select id="selectall4m" resultmap="personmap">
    select *
    from `person`
select>

在接口中增加对应的方法

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:47
 */
public interface personmapper {
    /**
     * 查询用户列表 resulttype
     *
     * @return
     */
    list<person> selectall4t();
    /**
     * 查询用户列表 resultmap
     *
     * @return
     */
    list<person> selectall4m();
}

测试 selectall4m 方法

@test
public void selectall4m(){
    // 获取该接口的代理对象
    personmapper mapper = sqlsession.getmapper(personmapper.class);
    // 执行接口中的方法
    list<person> people = mapper.selectall4m();
    // 释放sqlsession资源
    sqlsession.close();
    // 遍历集合
    people.foreach(system.out::println);
}
配置 mapunderscoretocamelcase 值为 true

在核心配置文件中配置此参数如下

<settings>
    
    <setting name="mapunderscoretocamelcase" value="true"/>
settings>

测试 selectall4t 方法

@test
public void selectall4t(){
    // 获取该接口的代理对象
    personmapper mapper = sqlsession.getmapper(personmapper.class);
    // 执行接口中的方法
    list<person> people = mapper.selectall4t();
    // 释放sqlsession资源
    sqlsession.close();
    // 遍历集合
    people.foreach(system.out::println);
}

在控制台显示log日志

在核心配置文件中 设置logimpl 的值为 stdout_logging

<settings>
    
    <setting name="logimpl" value="stdout_logging"/>
settings>

完整的核心配置文件

src/main/resources/mybatis/myatis-confog.xml


doctype configuration
        public "-//mybatis.org//dtd config 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <properties resource="config.properties" />
    <settings>
        
        <setting name="mapunderscoretocamelcase" value="true"/>
        
        <setting name="logimpl" value="stdout_logging"/>
    settings>
    
    
    <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>
        
        
        
        
        
        
        
        <package name="com.lihaozhe.mapper"/>
    mappers>
configuration>

select

编写接口

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import org.apache.ibatis.annotations.param;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/6 上午8:52
 */
public interface personmapper {
    /**
     * 根据手机号查询用户信息
     * @param mobile
     * @return
     */
    person selectbymobile(@param("mobile") string mobile);
}

编写映射配置文件

src/main/resources/com/lihaozhe/mapper/personmapper.xml

默认情况下,使用 #{} 参数语法时,mybatis 会创建 preparedstatement 参数占位符,并通过占位符安全地设置参数(就像使用 ? 一样)。


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.personmapper">
    
    <select id="selectbymobile" parametertype="java.lang.string" resulttype="com.lihaozhe.pojo.person">
        select *
        from `person`
		where `mobile` = #{mobile}>
    select>
mapper>

mybatis

测试类

com.lihaozhe.mapper.personmappertest

注意:测试方法中获取sqlsession对象

@test
public void selectbymobile(){
    // 获取该接口的代理对象
    personmapper mapper = sqlsession.getmapper(personmapper.class);
    // 执行接口中的方法
    person person = mapper.selectbymobile("13925135946");
    // 释放sqlsession资源
    sqlsession.close();
    // 输出查询结果
    system.out.println(person);
}

#与$的区别

默认情况下,使用 #{} 参数语法时,mybatis 会创建 preparedstatement 参数占位符,并通过占位符安全地设置参数(就像使用 ? 一样)。

这样做更安全,更迅速,通常也是首选做法,不过有时你就是想直接在 sql 语句中直接插入一个不转义的字符串。

比如 order by 子句,mybatis 就不会修改或转义该字符串了。

需求:查询的条件字段和该字段的值不确定

编写接口

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import org.apache.ibatis.annotations.param;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/6 上午8:52
 */
public interface personmapper {
   /**
     * 根据不确定的字段查询
     * @param column
     * @param value
     * @return
     */
    person selectbyfiled(@param("column") string column,@param("value")string value);
}

编写映射配置文件

src/main/resources/com/lihaozhe/mapper/personmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.personmapper">
	
    <select id="selectbyfiled" resulttype="com.lihaozhe.pojo.person">
        select *
        from `person`
        where ${column} = #{value}
    select>
mapper>

测试类

com.lihaozhe.mapper.personmappertest

注意:测试方法中获取sqlsession对象

@test
public void selectbyfiled() {
    // 获取该接口的代理对象
    personmapper mapper = sqlsession.getmapper(personmapper.class);
    // 执行接口中的方法
    person person = mapper.selectbyfiled("mobile", "18400880850");
    // 释放sqlsession资源
    sqlsession.close();
    // 输出查询结果
    system.out.println(person);
}

解析结果:

==>  preparing: select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where mobile = ?
==> parameters: 18400880850(string)

mybatis#与$区别

别名映射

起因:parametertype 和 resulttype 的值 需要使用类的完全限定名 太麻烦 希望使用 简短的名字来替代 类的完全限定名

在核心配置文件中 配置如下内容:

<typealiases>
    
    
    <typealias alias="login" type="com.lihaozhe.pojo.login"/>
typealiases>

编写接口

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.login;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 上午8:52
 */
public interface personmapper {
    /**
     * 根据唯一身份标识符用户信息
     *
     * @param uuid
     * @return
     */
    person selectbyuuid(@param("uuid") string uuid);;
}

编写映射配置文件

src/main/resources/com/lihaozhe/mapper/personmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.personmapper">
    
    <select id="selectbyuuid" resulttype="person">
        select *
        from `person`
        where uuid = #{uuid}
    select>
mapper>

测试类

com.lihaozhe.mapper.personmappertest

注意:测试方法中获取sqlsession对象

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.login;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/6 上午8:52
 */
public class loginmappertest {
    private sqlsession sqlsession;
    // junit5 @beforeall和@beforeeach注解替换了 junit4 中的@before注解。
    // 它⽤于表⽰应在当前类中的每个@test⽅法之前执⾏注解⽅法。
    // 注意:@beforeall注解的⽅法必须为静态⽅法,否则它将引发运⾏时错误。
    // 注意:@beforeeach注解的⽅法不得为静态⽅法,否则它将引发运⾏时错误。
    @beforeeach
    public void opensqlsession() throws ioexception {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = resources.getresourceasreader(resource);
        // 构建会话工厂
        sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        // 从sqlsessionfactory对象中获取sqlsession
        sqlsession = sqlsessionfactory.opensession();
    }
    @test
    public void selectbypid(){
        loginmapper mapper = sqlsession.getmapper(loginmapper.class);
        login login = mapper.selectbypid(3);
        sqlsession.close();
        system.out.println(login);
    }
}

某个包下所有类做别名映射

起因:在核心配置文件中单独为某个类做别名映射 如果需要映射的类太多 则过于麻烦 可以指定某个包面所有的类指定别名映射

<typealiases>
    
    
    
    
    <package name="com.lihaozhe.pojo"/>
typealiases>

完整核心配置文件

src/main/resources/mybatis/myatis-confog.xml


doctype configuration
        public "-//mybatis.org//dtd config 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <properties resource="config.properties" />
    <settings>
        
        <setting name="mapunderscoretocamelcase" value="true"/>
        
        <setting name="logimpl" value="stdout_logging"/>
    settings>
    <typealiases>
        
        
        
        
        <package name="com.lihaozhe.pojo"/>
    typealiases>
    
    
    <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>
        
        
        
        
        
        
        
        <package name="com.lihaozhe.mapper"/>
    mappers>
configuration>

insert

编写接口

com.lihaozhe.mapper.deptmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.dept;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/6 上午8:52
 */
public interface deptmapper {
    /**
     * 新增部门
     *
     * @param dept
     * @return
     */
    int insert(@param("dept") dept dept);
}

编写映射配置文件

src/main/resources/com/lihaozhe/mapper/deptmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.deptmapper">
    
    <insert id="insert">
        insert into `dept` (`dname`)
        values (#{dept.dname})
    insert>
mapper>

测试类

com.lihaozhe.mapper.deptmappertest

注意:测试方法中获取sqlsession对象

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.dept;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/6 上午8:52
 */
public class deptmappertest {
    private sqlsession sqlsession;
    // junit5 @beforeall和@beforeeach注解替换了 junit4 中的@before注解。
    // 它⽤于表⽰应在当前类中的每个@test⽅法之前执⾏注解⽅法。
    // 注意:@beforeall注解的⽅法必须为静态⽅法,否则它将引发运⾏时错误。
    // 注意:@beforeeach注解的⽅法不得为静态⽅法,否则它将引发运⾏时错误。
    @beforeeach
    public void opensqlsession() throws ioexception {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = resources.getresourceasreader(resource);
        // 构建会话工厂
        sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        // 从sqlsessionfactory对象中获取sqlsession
        sqlsession = sqlsessionfactory.opensession();
    }
    @test
    public void insert(){
        // 获取代理对象
        deptmapper mapper = sqlsession.getmapper(deptmapper.class);
        // 准备数据
        dept dept = new dept("人事部");
        // 插入之前 输出准备数据
        system.out.println("插入之前 dept >>> "  dept);
        // 调用方法执行 insert 操作
        mapper.insert(dept);
        // 手动提交事务
        sqlsession.commit();
        // 释放资源
        sqlsession.close();
        // 插入之后 输出准备数据
        system.out.println("插入之后 dept >>> "  dept);
    }
}

解析结果:

插入之前 dept >>> dept(did=0, dname=人事部)
opening jdbc connection
created connection 671596011.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@2807bdeb]
==>  preparing: insert into `dept` (`dname`) values (?)
==> parameters: 人事部(string)
<==    updates: 1
committing jdbc connection [com.mysql.cj.jdbc.connectionimpl@2807bdeb]
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@2807bdeb]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@2807bdeb]
returned connection 671596011 to pool.
插入之后 dept >>> dept(did=0, dname=人事部)

新增数据后获取新增数据主键值


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.deptmapper">
    
    
    <insert id="insert" parametertype="dept" usegeneratedkeys="true" keyproperty="did" keycolumn="did">
        insert into `dept` (`dname`)
        values (#{dept.dname})
    insert>
mapper>

解析结果:

插入之前 dept >>> dept(did=0, dname=摸鱼部)
opening jdbc connection
created connection 1643141512.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@61f05988]
==>  preparing: insert into `dept` (`dname`) values (?)
==> parameters: 摸鱼部(string)
<==    updates: 1
committing jdbc connection [com.mysql.cj.jdbc.connectionimpl@61f05988]
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@61f05988]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@61f05988]
returned connection 1643141512 to pool.
插入之后 dept >>> dept(did=8, dname=摸鱼部)

update

编写接口

com.lihaozhe.mapper.deptmappe

package com.lihaozhe.mapper;
import cn.hutool.core.collection.lineiter;
import com.lihaozhe.pojo.dept;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/6 上午8:52
 */
public interface deptmapper {
    /**
     * 修改部门信息
     *
     * @param dept
     * @return
     */
    int update(@param("dept") dept dept);
}

编写映射配置文件

src/main/resources/com/lihaozhe/mapper/deptmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.deptmapper">
    
    <update id="update">
        update `dept`
        set `dname` = #{dept.dname}
        where `did` = #{dept.did}
    update>
mapper>

测试类

com.lihaozhe.mapper.deptmappetest

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.dept;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/6 上午8:52
 */
public class deptmappertest {
    private sqlsession sqlsession;
    // junit5 @beforeall和@beforeeach注解替换了 junit4 中的@before注解。
    // 它⽤于表⽰应在当前类中的每个@test⽅法之前执⾏注解⽅法。
    // 注意:@beforeall注解的⽅法必须为静态⽅法,否则它将引发运⾏时错误。
    // 注意:@beforeeach注解的⽅法不得为静态⽅法,否则它将引发运⾏时错误。
    @beforeeach
    public void getsqlsession() throws ioexception {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = resources.getresourceasreader(resource);
        // 构建会话工厂
        sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        // 从sqlsessionfactory对象中获取sqlsession
        sqlsession = sqlsessionfactory.opensession();
    }
    @test
    public void update() {
        // 获取代理对象
        deptmapper mapper = sqlsession.getmapper(deptmapper.class);
        // 准备数据
        dept dept = new dept(8, "企宣部");
        // 调用方法执行 update 操作
        mapper.update(dept);
        // 手动提交事务
        sqlsession.commit();
        // 释放资源
        sqlsession.close();
    }
}

delete

编写接口

com.lihaozhe.mapper.deptmappe

package com.lihaozhe.mapper;
import cn.hutool.core.collection.lineiter;
import com.lihaozhe.pojo.dept;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/6 上午11:13
 */
public interface deptmapper {
    /**
     * 根据部门id删除部门
     *
     * @param did
     * @return
     */
    int deletebydid(@param("did") long did);
}

编写映射配置文件

src/main/resources/com/lihaozhe/mapper/deptmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.deptmapper">
   
   <delete id="deletebydid">
        delete
        from `dept`
        where `did` = #{did}
    delete>
mapper>

测试类

com.lihaozhe.mapper.deptmappetest

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.dept;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午3:56
 */
public class deptmappertest {
    private sqlsession sqlsession;
    // junit5 @beforeall和@beforeeach注解替换了 junit4 中的@before注解。
    // 它⽤于表⽰应在当前类中的每个@test⽅法之前执⾏注解⽅法。
    // 注意:@beforeall注解的⽅法必须为静态⽅法,否则它将引发运⾏时错误。
    // 注意:@beforeeach注解的⽅法不得为静态⽅法,否则它将引发运⾏时错误。
    @beforeeach
    public void getsqlsession() throws ioexception {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = resources.getresourceasreader(resource);
        // 构建会话工厂
        sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        // 从sqlsessionfactory对象中获取sqlsession
        sqlsession = sqlsessionfactory.opensession();
    }
    @test
    public void deletebydid(){
        // 获取代理对象
        deptmapper mapper = sqlsession.getmapper(deptmapper.class);
        // 调用方法执行 delete 操作
        mapper.deletebydid(8);
        // 手动提交事务
        sqlsession.commit();
        // 释放资源
        sqlsession.close();
    }
}

工具类

com.lihaozhe.util.mybatis.mybatisutil

package com.lihaozhe.util.mybatis;
import org.apache.ibatis.io.resources;
import org.apache.ibatis.session.executortype;
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.reader;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/13 上午11:39
 */
public abstract class mybatisutil {
    private static threadlocal<sqlsession> threadlocal = new threadlocal<>();
    private static sqlsessionfactory sqlsessionfactory;
    private static sqlsession sqlsession;
    static {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = null;
        try {
            reader = resources.getresourceasreader(resource);
            // 构建会话工厂
            sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        } catch (ioexception e) {
            throw new runtimeexception(e);
        }
    }
    /**
     * 获取 sqlsession 对象
     *
     * @return sqlsession 对象
     */
    public static sqlsession opensqlsession() {
        if (threadlocal.get() == null) {
            // 从sqlsessionfactory对象中获取sqlsession
            sqlsession = sqlsessionfactory.opensession();
            // 与线程绑定
            threadlocal.set(sqlsession);
            // 返回 sqlsession 对象
            return sqlsession;
        } else {
            return threadlocal.get();
        }
    }
    /**
     * 获取 sqlsession 对象
     *
     * @param executortype simple,reuse,batch
     * @return sqlsession 对象
     */
    public static sqlsession opensqlsession(executortype executortype) {
        if (threadlocal.get() == null) {
            // 从sqlsessionfactory对象中获取sqlsession
            sqlsession = sqlsessionfactory.opensession(executortype);
            // 与线程绑定
            threadlocal.set(sqlsession);
            // 返回 sqlsession 对象
            return sqlsession;
        } else {
            return threadlocal.get();
        }
    }
    /**
     * 释放资源
     */
    public static void close() {
        if (threadlocal.get() != null) {
            sqlsession = threadlocal.get();
            threadlocal.remove();
            sqlsession.close();
        }
    }
    /**
     * 事务提交 释放资源
     */
    public static void commitandclose() {
        if (threadlocal.get() != null) {
            sqlsession = threadlocal.get();
            threadlocal.remove();
            sqlsession.commit();
            sqlsession.close();
        }
    }
    /**
     * 事务回滚 释放资源
     */
    public static void rollbackandclose() {
        if (threadlocal.get() != null) {
            sqlsession = threadlocal.get();
            threadlocal.remove();
            sqlsession.rollback();
            sqlsession.close();
        }
    }
}

动态sql

课工场 layui

@test
public void test() {
    // 需求:查询某部门的(did)  名字有某个字的(ename) 员工列表
    // 分析:
    // 如果不给部门编号则在所有部门中查找 did  不能为 0
    // 如果有部门编号则在某部门内查找
    long did = 3;
    stringbuilder sql = new stringbuilder("select * from person where ");
    if (did != 0) {
        sql.append(" did = ?");
        sql.append(" and ename like ");
        sql.append(" '%");
        sql.append(" ? ");
        sql.append("%' ");
    }else {
        sql.append(" ename like ");
        sql.append(" '%");
        sql.append(" ? ");
        sql.append("%' ");
    }
    system.out.println(sql.tostring());
    // select * from person where  ename like  %  ?  % 
    // select * from person where  did = ? and ename like  %  ?  % 
}

起因:根据不同的查询条件生成不同的sql语句

sql片段

将经常使用的sql语句定义成sql片段当使用的时候引导该片段即可 有点像 变量的赋值与引用

编写接口

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import org.apache.ibatis.annotations.param;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:47
 */
public interface personmapper {
    /**
     * 根据用户id查询该用户信息 使用sql片段
     *
     * @return
     */
    person selectbyid(@param("id") long id);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/personmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.personmapper">
    
    <sql id="select_person">
        select *
        from `person`
    sql>
    
    <select id="selectbyid" resulttype="person">
        <include refid="select_person">include>
        where `id` = #{id}
    select>
mapper>
编写测试类

com.lihaozhe.mapper.personmappertest

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:51
 */
public class personmappertest {
    private sqlsession sqlsession;
    // junit5 @beforeall和@beforeeach注解替换了 junit4 中的@before注解。
    // 它⽤于表⽰应在当前类中的每个@test⽅法之前执⾏注解⽅法。
    // 注意:@beforeall注解的⽅法必须为静态⽅法,否则它将引发运⾏时错误。
    // 注意:@beforeeach注解的⽅法不得为静态⽅法,否则它将引发运⾏时错误。
    @beforeeach
    public void opensqlsession() throws ioexception {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = resources.getresourceasreader(resource);
        // 构建会话工厂
        sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        // 从sqlsessionfactory对象中获取sqlsession
        sqlsession = sqlsessionfactory.opensession();
    }
    
    @test
    public void selectbyid() {
        // 获取该接口的代理对象
        personmapper mapper = sqlsession.getmapper(personmapper.class);
        // 执行接口中的方法
        person person = mapper.selectbyid(3);
        // 释放sqlsession资源
        sqlsession.close();
        // 输出查询结果
        system.out.println(person);
    }
}

sql解析结果:

==>  preparing: select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `id` = ?
==> parameters: 3(long)
<==    columns: id, uuid, mobile, nickname, id_card
<==        row: 3, 5bc69d3c6aba4a61a81115ba916237f3, 13925135946, 邹庶, 313227198110042264
<==      total: 1

sql片段

bind

编写接口

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import org.apache.ibatis.annotations.param;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:47
 */
public interface personmapper {
    /**
     * 模糊查找某姓名中包含某个字的用户
     *
     * @param nickname
     * @return
     */
    list<person> selectbynickname(@param("nickname") string nickname);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/personmapper.xml


<sql id="select_person">
    select *
    from `person`
sql>
<select id="selectbynickname" resulttype="person">
    
    <select id="selectbynickname" resulttype="person">
        <bind name="like_nickname" value="'%'   nickname   '%'"/>
        <include refid="select_person">include>
        where `nickname` like #{like_nickname}
    select>
select>

注意:在bind标签中value属性获取值的时候不需要使用#

编写测试类

com.lihaozhe.mapper.personmappertest

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:51
 */
public class personmappertest {
    private sqlsession sqlsession;
    // junit5 @beforeall和@beforeeach注解替换了 junit4 中的@before注解。
    // 它⽤于表⽰应在当前类中的每个@test⽅法之前执⾏注解⽅法。
    // 注意:@beforeall注解的⽅法必须为静态⽅法,否则它将引发运⾏时错误。
    // 注意:@beforeeach注解的⽅法不得为静态⽅法,否则它将引发运⾏时错误。
    @beforeeach
    public void getsqlsession() throws ioexception {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = resources.getresourceasreader(resource);
        // 构建会话工厂
        sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        // 从sqlsessionfactory对象中获取sqlsession
        sqlsession = sqlsessionfactory.opensession();
    }
    @test
    public void selectbynickname() {
        // 获取接口代理对象
        personmapper mapper = sqlsession.getmapper(personmapper.class);
        // 准备数据集
        string nickname = "孙";
        // %孙%
        stringbuilder param = new stringbuilder();
        param.append("%");
        if (!stringutils.isempty(nickname)) {
            param.append(nickname);
        }
        param.append("%");
        // 执行代理对象中的方法
        list<person> personlist = mapper.selectbynickname(param.tostring());
        // 释放资源
        sqlsession.close();
        // 输出结果
        personlist.foreach(system.out::println);
    }
}
package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:51
 */
public class personmappertest {
    private sqlsession sqlsession;
    // junit5 @beforeall和@beforeeach注解替换了 junit4 中的@before注解。
    // 它⽤于表⽰应在当前类中的每个@test⽅法之前执⾏注解⽅法。
    // 注意:@beforeall注解的⽅法必须为静态⽅法,否则它将引发运⾏时错误。
    // 注意:@beforeeach注解的⽅法不得为静态⽅法,否则它将引发运⾏时错误。
    @beforeeach
    public void getsqlsession() throws ioexception {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = resources.getresourceasreader(resource);
        // 构建会话工厂
        sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        // 从sqlsessionfactory对象中获取sqlsession
        sqlsession = sqlsessionfactory.opensession();
    }
    @test
    public void selectbynickname() {
       // 获取接口代理对象
        personmapper mapper = sqlsession.getmapper(personmapper.class);
        // 执行代理对象中的方法
        list<person> personlist = mapper.selectbynickname("孙");
        // 释放资源
        sqlsession.close();
        // 输出结果
        personlist.foreach(system.out::println);
    }
}

结果解析:

==>  preparing: select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `nickname` like ?
==> parameters: %孙%(string)
<==    columns: id, uuid, mobile, nickname, id_card
<==        row: 2, 82bbfb207b38447e93fffe3c53ba3e5b, 15051340785, 孙陈, 919948197901282822
<==        row: 31, 3db353f3b81b44c6bc6095487d8a5b05, 13628389232, 孙鹃祈, 314211197412052754
<==        row: 72, 2032a25e5245454894e192d8d5b17147, 13352587230, 孙茎, 453355198107241539
<==      total: 3

if

编写接口

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import org.apache.ibatis.annotations.param;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:47
 */
public interface personmapper {
    
    /**
     * 模糊查找某姓名中包含某个字的男性或女性用户
     *
     * @param nickname
     * @return
     */
    list<person> selectbygenderandnickname(@param("gender") integer gender, @param("nickname") string nickname);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/personmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.personmapper">
    
    <sql id="select_person">
        select *
        from `person`
    sql>
    
    <select id="selectbygenderandnickname" resulttype="person">
        <include refid="select_person">include>
        where
        <if test="gender != null">
            if(mod(substr(id_card, 17, 1), 2), 1, 0) = #{gender}
        if>
        <if test="nickname != null and nickname.length > 0">
            <bind name="like_nickname" value="'%'   nickname   '%'"/>
            and `nickname` like #{like_nickname}
        if>
    select>
mapper>

结果解析:

-- 当方法中参数nickname的值为null或者字符串长度为零
select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `gender` = ?
-- 当方法中参数nickname的值不为null且字符串长度大于零
select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `gender` = ? and `nickname` like ?
编写测试类

com.lihaozhe.mapper.personmappertest

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:51
 */
public class personmappertest {
    private sqlsession sqlsession;
    // junit5 @beforeall和@beforeeach注解替换了 junit4 中的@before注解。
    // 它⽤于表⽰应在当前类中的每个@test⽅法之前执⾏注解⽅法。
    // 注意:@beforeall注解的⽅法必须为静态⽅法,否则它将引发运⾏时错误。
    // 注意:@beforeeach注解的⽅法不得为静态⽅法,否则它将引发运⾏时错误。
    @beforeeach
    public void oepnsqlsession() throws ioexception {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = resources.getresourceasreader(resource);
        // 构建会话工厂
        sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        // 从sqlsessionfactory对象中获取sqlsession
        sqlsession = sqlsessionfactory.opensession();
    }
    @test
    public void selectbygenderandnickname() {
        // 获取接口代理对象
        personmapper mapper = sqlsession.getmapper(personmapper.class);
        // 执行代理对象中的方法
        // list personlist = mapper.selectbygenderandnickname(0,null);
           list<person> personlist = mapper.selectbygenderandnickname(1,"孙");
        // 释放资源
        sqlsession.close();
        // 输出结果
        personlist.foreach(system.out::println);
    }
}

where

使用上面if相同的方法selectbygenderandnickname和配置文件

当两个参数同时为null的时候sql语句为 :

select * from `perason` where 

这条sql语句存在语法错误 当没有查询条件的时候做出如下配置


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.personmapper">
    
    <sql id="select_person">
        select *
        from `person`
    sql>
    
    <select id="selectbygenderandnickname" resulttype="person">
        <include refid="select_person">include>
        where
        <if test="gender != null">
            if(mod(substr(id_card, 17, 1), 2), 1, 0) = #{gender}
        if>
        <if test="nickname != null and nickname.length > 0">
            <bind name="like_nickname" value="'%'   nickname   '%'"/>
            and `nickname` like #{like_nickname}
        if>
    select>
mapper>

choose (when, otherwise)

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

需求:id, uuid, mobile 多个查询条件选择其中一个

编写接口

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import org.apache.ibatis.annotations.param;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:47
 */
public interface personmapper {
    /**
     * `id`, `uuid`, `mobile` 多个查询条件选择其中一个
     * @param person
     * @return
     */
    person selectbyidoruuidormobile(@param("person") person person);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/personmapper.xml


<sql id="select_person">
    select *
    from `person`
sql>
<select id="selectbyidoruuidormobile" resulttype="person">
    <include refid="select_person">include>
    <where>
        <choose>
            <when test="person.id != null and person.id > 0">
                `id` = #{person.id}
            when>
            <when test="person.uuid != null and person.uuid.length > 0">
                `uuid` = #{person.uuid}
            when>
            <otherwise>
                `mobile` = #{person.mobile}
            otherwise>
        choose>
    where>
select>

解析结果:

-- 只传入mobile
select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `mobile` = ?
-- 传入uuid
select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `uuid` = ?
-- 传入id
select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `id` = ?
编写测试类

com.lihaozhe.mapper.personmappertest

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:51
 */
public class personmappertest {
    private sqlsession sqlsession;
    // junit5 @beforeall和@beforeeach注解替换了 junit4 中的@before注解。
    // 它⽤于表⽰应在当前类中的每个@test⽅法之前执⾏注解⽅法。
    // 注意:@beforeall注解的⽅法必须为静态⽅法,否则它将引发运⾏时错误。
    // 注意:@beforeeach注解的⽅法不得为静态⽅法,否则它将引发运⾏时错误。
    @beforeeach
    public void opensqlsession() throws ioexception {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = resources.getresourceasreader(resource);
        // 构建会话工厂
        sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        // 从sqlsessionfactory对象中获取sqlsession
        sqlsession = sqlsessionfactory.opensession();
    }
    @test
    public void selectbyidoruuidormobile() {
        // 获取该接口的代理对象
        personmapper mapper = sqlsession.getmapper(personmapper.class);
        // 准备数据
        person person = new person();
        // select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `mobile` = ?
        person.setmobile("13352587230");
        // select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `uuid` = ?
		person.setuuid("2032a25e5245454894e192d8d5b17147");
        // select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `id` = ?
        person.setid(33);
        // 执行接口中的方法
        person = mapper.selectbyidoruuidormobile(person);
        // select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `nickname` like ?
        // 释放sqlsession资源
        sqlsession.close();
        // 输出查询结果
        system.out.println(person);
    }
}

trim

编写接口

com.lihaozhe.mapper.empmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.emp;
import org.apache.ibatis.annotations.param;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/8 上午10:32
 */
public interface empmapper {
    /**
     * 动态sql if 按照部门id和姓名中部分关键字查找
     * 如果没有传递部门id则在所有部门中查找
     * 如果传递部门id但没有传递姓名中的关键字则查找该部门下所有员工列表
     * 如果部门id和姓名中的关键字都没有传递则查找所有员工列表
     *
     * @param emp
     * @return
     */
    list<emp> selcetbydidandename(@param("emp") emp emp);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/empmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.empmapper">
    
    <select id="selectbydidandename" resulttype="emp">
        select * from `emp`
        <trim prefix="where" prefixoverrides="and|or">
            <if test="emp.did != null and emp.did > 0">
                `did` = #{emp.did}
            if>
            <if test="emp.ename != null and emp.ename.length > 0">
                <bind name="like_ename" value="'%'   emp.ename   '%'"/>
                and `ename` like #{like_ename}
            if>
        trim>
    select>
mapper>

解析 结果:

-- ename 孙
select `eid`, `ename`, `did` from `emp` where `ename` like ?
-- ename ""
select `eid`, `ename`, `did` from `emp`
-- did 3
select `eid`, `ename`, `did` from `emp` where `did` = ?
-- did 3 并且 ename 孙
select `eid`, `ename`, `did` from `emp` where `did` = ? and `ename` like ?
编写测试类

com.lihaozhe.mapper.empmappertest

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.emp;
import com.lihaozhe.util.mybatis.mybatisutil;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/8 下午12:02
 */
public class empmappertest {
    @test
    public void selcetbydidandename(){
        // 使用工具类获取 sqlsession 对象
        sqlsession sqlsession = mybatisutil.getsqlsession();
        // 获取接口代理对象
        empmapper mapper = sqlsession.getmapper(empmapper.class);
        // 准备数据
        emp emp = new emp();
        // select `eid`, `ename`, `did` from `emp` where `ename` like ?
        emp.setename("孙");
        // select `eid`, `ename`, `did` from `emp`
        // emp.setename("");
        // select `eid`, `ename`, `did` from `emp` where `did` = ?
        emp.setdid(3);
        // select `eid`, `ename`, `did` from `emp` where `did` = ? and `ename` like ?
        // 执行 接口 中的方法
        list<emp> emps = mapper.selcetbydidandename(emp);
        // 使用工具类 释放资源
        mybatisutil.close();
        // 输出结果
        emps.foreach(system.out::println);
    }
}

set

用于动态更新语句的类似龙8唯一官网的解决方案叫做 set, set 元素可以用于动态包含需要更新的列,忽略其它不更新的列。

需求:更新 person表 中的个别字段

编写接口

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import org.apache.ibatis.annotations.param;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:47
 */
public interface personmapper {
    
    /**
     * 修改员工表数据
     *
     * @param person
     * @return
     */
    int updatebyid(@param("person") person person);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/personmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.personmapper">
    
    <update id="updatebyid" parametertype="person">
        update `person`
        <set>
            <if test="person.nickname != null and person.nickname.length > 0">
                `nickname` = #{person.nickname},
            if>
            <if test="person.mobile != null and person.mobile.length == 11">
                `mobile` = #{person.mobile},
            if>
            <if test="person.idcard != null and (person.idcard.length == 18 or person.idcard.length == 15)">
                `id_card` = #{person.idcard}
            if>
        set>
        where `id` = #{person.id}
    update>
mapper>

或者:


<update id="updatebyid">
    update `person`
    <trim prefix="set" suffixoverrides=",">
        <if test="person.nickname != null and person.nickname.length > 0">
            `nickname` = #{person.nickname},
        if>
        <if test="person.mobile != null and person.mobile.length == 11">
            `mobile` = #{person.mobile},
        if>
        <if test="person.idcard != null and (person.idcard.length == 18 or person.idcard.length == 15)">
            `id_card` = #{person.idcard}
        if>
    trim>
    where `id` = #{person.id}
update>
编写测试类

com.lihaozhe.mapper.personmappertest

package com.lihaozhe.mapper;
import cn.binarywang.tools.generator.chineseidcardnumbergenerator;
import cn.binarywang.tools.generator.chinesemobilenumbergenerator;
import cn.binarywang.tools.generator.chinesenamegenerator;
import cn.hutool.core.util.idutil;
import com.lihaozhe.pojo.person;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
import java.util.arraylist;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:51
 */
public class personmappertest {
    private sqlsession sqlsession;
    // junit5 @beforeall和@beforeeach注解替换了 junit4 中的@before注解。
    // 它⽤于表⽰应在当前类中的每个@test⽅法之前执⾏注解⽅法。
    // 注意:@beforeall注解的⽅法必须为静态⽅法,否则它将引发运⾏时错误。
    // 注意:@beforeeach注解的⽅法不得为静态⽅法,否则它将引发运⾏时错误。
    @beforeeach
    public void opensqlsession() throws ioexception {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = resources.getresourceasreader(resource);
        // 构建会话工厂
        sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        // 从sqlsessionfactory对象中获取sqlsession
        sqlsession = sqlsessionfactory.opensession();
    }
    @test
    public void updatebyid() {
        // 获取该接口的代理对象
        personmapper mapper = sqlsession.getmapper(personmapper.class);
        // 准备数据
        person person = new person();
        string mobile = chinesemobilenumbergenerator.getinstance().generate();
        system.out.println(mobile);
        // update `person` set `mobile` = ? where `id` = ?
        person.setmobile(mobile);
        person.setid(3);
        // 执行接口中的方法
        mapper.updatebyid(person);
        // 事务提交
        sqlsession.commit();
        // 释放sqlsession资源
        sqlsession.close();
        // 输出结果
        if (status > 0) {
            system.out.println("☺");
        } else {
            system.out.println("o(╯□╰)o");
        }
    }
}

foreach

select
编写接口

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import org.apache.ibatis.annotations.param;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:47
 */
public interface personmapper {
    /**
     * 查找多个id的用户列表
     *
     * @param ids
     * @return
     */
    list<person> selectbyids(@param("ids") long... ids);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/personmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.personmapper">
	 
    <sql id="select_person">
        select *
        from `person`
    sql>
    
    <select id="selectbyids" resulttype="person">
        <include refid="select_person">include>
        <where>
            `id` in
            <foreach collection="ids" index="index" item="id" open="(" separator="," close=")">
                #{id}
            foreach>
        where>
    select>
mapper>
编写测试类

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import cn.binarywang.tools.generator.chineseidcardnumbergenerator;
import cn.binarywang.tools.generator.chinesemobilenumbergenerator;
import cn.binarywang.tools.generator.chinesenamegenerator;
import cn.hutool.core.util.idutil;
import com.lihaozhe.pojo.person;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
import java.util.arraylist;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:51
 */
public class personmappertest {
    private sqlsession sqlsession;
    // junit5 @beforeall和@beforeeach注解替换了 junit4 中的@before注解。
    // 它⽤于表⽰应在当前类中的每个@test⽅法之前执⾏注解⽅法。
    // 注意:@beforeall注解的⽅法必须为静态⽅法,否则它将引发运⾏时错误。
    // 注意:@beforeeach注解的⽅法不得为静态⽅法,否则它将引发运⾏时错误。
    @beforeeach
    public void opensqlsession() throws ioexception {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = resources.getresourceasreader(resource);
        // 构建会话工厂
        sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        // 从sqlsessionfactory对象中获取sqlsession
        sqlsession = sqlsessionfactory.opensession();
    }
    @test
    public void selectbyids() {
        // 获取该接口的代理对象
        personmapper mapper = sqlsession.getmapper(personmapper.class);
        // 执行接口中的方法
        list<person> personlist = mapper.selectbyids(1l, 3l, 5l);
        // 释放sqlsession资源
        sqlsession.close();
        // 输出查询结果
        personlist.foreach(system.out::println);
    }
}
delete
编写接口

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import org.apache.ibatis.annotations.param;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:47
 */
public interface personmapper {
  
    /**
     * 根据传入的id删除用户
     *
     * @param ids
     * @return
     */
    int delbyids(@param("ids") long... ids);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/personmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.personmapper">
    
    <delete id="delbyids">
        delete from `person`
        <where>
            `id` in
            <foreach collection="ids" index="index" item="id" open="(" separator="," close=")">
                #{id}
            foreach>
        where>
    delete>
mapper>
编写测试类

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import cn.binarywang.tools.generator.chineseidcardnumbergenerator;
import cn.binarywang.tools.generator.chinesemobilenumbergenerator;
import cn.binarywang.tools.generator.chinesenamegenerator;
import cn.hutool.core.util.idutil;
import com.lihaozhe.pojo.person;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
import java.util.arraylist;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:51
 */
public class personmappertest {
    private sqlsession sqlsession;
    // junit5 @beforeall和@beforeeach注解替换了 junit4 中的@before注解。
    // 它⽤于表⽰应在当前类中的每个@test⽅法之前执⾏注解⽅法。
    // 注意:@beforeall注解的⽅法必须为静态⽅法,否则它将引发运⾏时错误。
    // 注意:@beforeeach注解的⽅法不得为静态⽅法,否则它将引发运⾏时错误。
    @beforeeach
    public void opensqlsession() throws ioexception {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = resources.getresourceasreader(resource);
        // 构建会话工厂
        sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        // 从sqlsessionfactory对象中获取sqlsession
        sqlsession = sqlsessionfactory.opensession();
    }
    @test
    public void delbyids() {
        // 获取该接口的代理对象
        personmapper mapper = sqlsession.getmapper(personmapper.class);
        // 执行接口中的方法
        mapper.delbyids(1l, 3l, 5l);
        // 事务提交
        sqlsession.commit();
        // 释放sqlsession资源
        sqlsession.close();
        // 输出结果
        if (status > 0) {
            system.out.println("☺");
            system.out.println(status  " 条记录被删除");
        } else {
            system.out.println("o(╯□╰)o");
        }
    }
}
insert

清空person表

truncate person;
编写接口

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import org.apache.ibatis.annotations.param;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:47
 */
public interface personmapper {
    /**
     * 新增用户列列表
     *
     * @param personlist
     * @return
     */
    int insertall(@param("personlist") list<person> personlist);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/personmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.personmapper">
    
    <insert id="insertall">
        insert into `person` (`uuid`,`mobile`,`nickname`,`id_card`) values
        <foreach collection="personlist" index="index" item="person" separator=",">
            (#{person.uuid},#{person.mobile},#{person.nickname},#{person.idcard})
        foreach>
    insert>
mapper>
编写测试类

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import cn.binarywang.tools.generator.chineseidcardnumbergenerator;
import cn.binarywang.tools.generator.chinesemobilenumbergenerator;
import cn.binarywang.tools.generator.chinesenamegenerator;
import cn.hutool.core.util.idutil;
import com.lihaozhe.pojo.person;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
import java.util.arraylist;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:51
 */
public class personmappertest {
    private sqlsession sqlsession;
    // junit5 @beforeall和@beforeeach注解替换了 junit4 中的@before注解。
    // 它⽤于表⽰应在当前类中的每个@test⽅法之前执⾏注解⽅法。
    // 注意:@beforeall注解的⽅法必须为静态⽅法,否则它将引发运⾏时错误。
    // 注意:@beforeeach注解的⽅法不得为静态⽅法,否则它将引发运⾏时错误。
    @beforeeach
    public void opensqlsession() throws ioexception {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = resources.getresourceasreader(resource);
        // 构建会话工厂
        sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        // 从sqlsessionfactory对象中获取sqlsession
        sqlsession = sqlsessionfactory.opensession();
    }
    @test
    public void insertall() {
        // 准备数据
        arraylist<person> personlist = new arraylist<>();
        for (int i = 0; i < 200; i) {
            person person = new person();
            person.setuuid(idutil.fastsimpleuuid());
            person.setmobile(chinesemobilenumbergenerator.getinstance().generate());
            person.setnickname(chinesenamegenerator.getinstance().generate());
            person.setidcard(chineseidcardnumbergenerator.getinstance().generate());
            system.out.println(person);
            personlist.add(person);
        }
        // 获取接口代理对象
        personmapper mapper = sqlsession.getmapper(personmapper.class);
        // 执行代理对象中的方法
        int status = mapper.insertall(personlist);
        // 事务提交
        sqlsession.commit();
        // 释放资源
        sqlsession.close();
        // 输出结果
        if (status > 0) {
            system.out.println("☺");
            system.out.println("新增了 "  status  " 条记录");
        } else {
            system.out.println("o(╯□╰)o");
        }
    }
}
性能
@test
public void testconetion() throws ioexception {
    // 核心配置文件classpath路径
    string resource = "mybatis/mybatis-config.xml";
    // 加载配置文件
    reader reader = resources.getresourceasreader(resource);
    // 构建会话工厂
    sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
    // 从sqlsessionfactory对象中获取sqlsession 同时设置批处理
    sqlsession sqlsession = sqlsessionfactory.opensession(executortype.batch);
    system.out.println(sqlsession.getconnection());
    // 归还连接给数据源
    sqlsession.close();
}
工具类修改
package com.lihaozhe.util.mybatis;
import org.apache.ibatis.io.resources;
import org.apache.ibatis.session.executortype;
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.reader;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/13 上午11:39
 */
public abstract class mybatisutil {
    private static threadlocal<sqlsession> threadlocal = new threadlocal<>();
    private static sqlsessionfactory sqlsessionfactory;
    private static sqlsession sqlsession;
    static {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = null;
        try {
            reader = resources.getresourceasreader(resource);
            // 构建会话工厂
            sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        } catch (ioexception e) {
            throw new runtimeexception(e);
        }
    }
    /**
     * 获取 sqlsession 对象
     *
     * @return sqlsession 对象
     */
    public static sqlsession opensqlsession() {
        if (threadlocal.get() == null) {
            // 从sqlsessionfactory对象中获取sqlsession
            sqlsession = sqlsessionfactory.opensession();
            // 与线程绑定
            threadlocal.set(sqlsession);
            // 返回 sqlsession 对象
            return sqlsession;
        } else {
            return threadlocal.get();
        }
    }
    /**
     * 获取 sqlsession 对象
     *
     * @param executortype simple,reuse,batch
     * @return sqlsession 对象
     */
    public static sqlsession opensqlsession(executortype executortype) {
        if (threadlocal.get() == null) {
            // 从sqlsessionfactory对象中获取sqlsession
            sqlsession = sqlsessionfactory.opensession(executortype);
            // 与线程绑定
            threadlocal.set(sqlsession);
            // 返回 sqlsession 对象
            return sqlsession;
        } else {
            return threadlocal.get();
        }
    }
    /**
     * 释放资源
     */
    public static void close() {
        if (threadlocal.get() != null) {
            sqlsession = threadlocal.get();
            threadlocal.remove();
            sqlsession.close();
        }
    }
    /**
     * 事务提交 释放资源
     */
    public static void commitandclose() {
        if (threadlocal.get() != null) {
            sqlsession = threadlocal.get();
            threadlocal.remove();
            sqlsession.commit();
            sqlsession.close();
        }
    }
    /**
     * 事务回滚 释放资源
     */
    public static void rollbackandclose() {
        if (threadlocal.get() != null) {
            sqlsession = threadlocal.get();
            threadlocal.remove();
            sqlsession.rollback();
            sqlsession.close();
        }
    }
}

select

一对一

resulttype
编写接口

com.lihaozhe.mapper.loginmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.login;
import com.lihaozhe.pojo.person;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午3:27
 */
public interface loginmapper {
    /**
     * 使用账号和密码登录 获取用户信息
     *
     * @param login 登录参数 account password
     * @return
     */
    person selectpersonbyaccountandpassword01(@param("login") login login);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/loginmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.loginmapper">
    
    <select id="selectpersonbyaccountandpassword01" resulttype="person">
        select p.id, nickname
        from login l
                 inner join person p
        where pid = p.id
          and account = #{login.account}
          and auth_text = #{login.authtext}
    select>
mapper>
编写测试类

com.lihaozhe.mapper.loginmapper.test

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.login;
import com.lihaozhe.pojo.person;
import com.lihaozhe.util.mybatis.mybatisutil;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午3:29
 */
public class loginmappertest {
    @test
    public void selectpersonbyaccountandpassword01(){
        login login = new login("13925135946", "123456");
        sqlsession sqlsession = mybatisutil.opensqlsession();
        loginmapper mapper = sqlsession.getmapper(loginmapper.class);
        person person = mapper.selectpersonbyaccountandpassword01(login);
        mybatisutil.close();
        system.out.println(person);
    }
}
resultmap 同一映射配置文件内
编写接口

com.lihaozhe.mapper.loginmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.login;
import com.lihaozhe.pojo.person;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午3:27
 */
public interface loginmapper {
    /**
     * 用户登录
     *
     * @param login 登录参数 account password
     * @return
     */
    person selectbyaccountandpassword02(@param("login") login login);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/loginmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.loginmapper">
    <resultmap id="personmap" type="person">
        <id property="id" column="id"/>
        <result property="uuid" column="uuid"/>
        <result property="mobile" column="mobile"/>
        <result property="nickname" column="nickname"/>
        <result property="idcard" column="id_card"/>
    resultmap>
    
    <select id="selectpersonbyaccountandpassword02" resultmap="personmap">
        select p.id, nickname
        from login l
                 inner join person p
        where pid = p.id
          and account = #{login.account}
          and auth_text = #{login.authtext}
    select>
mapper>
编写测试类

com.lihaozhe.mapper.loginmapper.test

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.login;
import com.lihaozhe.pojo.person;
import com.lihaozhe.util.mybatis.mybatisutil;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午3:29
 */
public class loginmappertest {
    @test
    public void selectpersonbyaccountandpassword02(){
        login login = new login("13925135946", "123456");
        sqlsession sqlsession = mybatisutil.opensqlsession();
        loginmapper mapper = sqlsession.getmapper(loginmapper.class);
        person person = mapper.selectpersonbyaccountandpassword02(login);
        mybatisutil.close();
        system.out.println(person);
    }
}
resultmap 跨射配置文件内
编写接口

com.lihaozhe.mapper.loginmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.login;
import com.lihaozhe.pojo.person;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午3:27
 */
public interface loginmapper {
    /**
     * 用户登录
     *
     * @param login 登录参数 account password
     * @return
     */
    person selectbyaccountandpassword03(@param("login") login login);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/loginmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.loginmapper">
    
    <select id="selectpersonbyaccountandpassword03" resultmap="com.lihaozhe.mapper.personmapper.personmap">
        select p.id, nickname
        from login l
                 inner join person p
        where pid = p.id
          and account = #{login.account}
          and auth_text = #{login.authtext}
    select>
mapper>
编写测试类

com.lihaozhe.mapper.loginmapper.test

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.login;
import com.lihaozhe.pojo.person;
import com.lihaozhe.util.mybatis.mybatisutil;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午3:29
 */
public class loginmappertest {
    @test
    public void selectpersonbyaccountandpassword03(){
        login login = new login("13925135946", "123456");
        sqlsession sqlsession = mybatisutil.opensqlsession();
        loginmapper mapper = sqlsession.getmapper(loginmapper.class);
        person person = mapper.selectpersonbyaccountandpassword03(login);
        mybatisutil.close();
        system.out.println(person);
    }
}
association
编写vo类

com.lihaozhe.vo.personvo

package com.lihaozhe.vo;
import com.lihaozhe.pojo.login;
import com.lihaozhe.pojo.person;
import lombok.allargsconstructor;
import lombok.data;
import lombok.noargsconstructor;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/10 下午2:19
 */
public class personvo implements serializable {
    private static final long serialversionuid = -2348274078216811958l;
    /**
     * 登录信息
     */
    private login login;
    /**
     * 员工信息
     */
    private person person;
}
编写接口

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import com.lihaozhe.vo.personvo;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午3:27
 */
public interface personmapper {
    /**
     * 根据id获取用户详细信息包括登录信息
     *
     * @param id 用户id
     * @return
     */
    personvo selectpersonvobyid(@param("id") long id);
}
在核心配置文件配置别名映射
<typealiases>
    <package name="com.lihaozhe.pojo"/>
    <package name="com.lihaozhe.vo"/>
typealiases>
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/personmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.personmapper">
    <resultmap id="personvomap" type="personvo">
        <association property="login">
            <id property="id" column="lid"/>
            <result property="account" column="account"/>
            <result property="authtext" column="auth_text"/>
            <result property="pid" column="pid"/>
        association>
        <association property="person">
            <id property="id" column="pid"/>
            <result property="uuid" column="uuid"/>
            <result property="mobile" column="mobile"/>
            <result property="nickname" column="nickname"/>
            <result property="idcard" column="id_card"/>
        association>
    resultmap>
    
    <select id="selectpersonvobyid" resultmap="personvomap">
        select l.id as lid,
               account,
               auth_text,
               pid,
               uuid,
               mobile,
               nickname,
               id_card
        from login l
                 inner join person p
        where pid = p.id
          and pid = #{id}
    select>
mapper>
编写测试类

com.lihaozhe.mapper.personmappertest

package com.lihaozhe.mapper;
import com.lihaozhe.vo.personvo;
import com.lihaozhe.util.mybatis.mybatisutil;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午3:29
 */
public class personmappertest {
    private sqlsession sqlsession;
    // junit5 @beforeall和@beforeeach注解替换了 junit4 中的@before注解。
    // 它⽤于表⽰应在当前类中的每个@test⽅法之前执⾏注解⽅法。
    // 注意:@beforeall注解的⽅法必须为静态⽅法,否则它将引发运⾏时错误。
    // 注意:@beforeeach注解的⽅法不得为静态⽅法,否则它将引发运⾏时错误。
    @beforeeach
    public void opensqlsession() throws ioexception {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = resources.getresourceasreader(resource);
        // 构建会话工厂
        sqlsessionfactory sessionfactory = new sqlsessionfactorybuilder().build(reader);
        // 从sqlsessionfactory对象中获取sqlsession
        sqlsession = sessionfactory.opensession();
    }
    
    @test
    public void selectpersonvobyid(){
        personmapper mapper = sqlsession.getmapper(personmapper.class);
        personvo personvo = mapper.selectpersonvobyid(3l);
        sqlsession.close();
        system.out.println(personvo);
    }
}

多对一

写法与一对一完全一致

下面的案例使用关联查询和子查询分别实现

编写vo类

com.lihaozhe.vo.sonvo

package com.lihaozhe.vo;
import com.lihaozhe.pojo.father;
import lombok.allargsconstructor;
import lombok.data;
import lombok.noargsconstructor;
import java.io.serializable;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/14 上午9:46
 */
@data
@noargsconstructor
@allargsconstructor
public class sonvo implements serializable {
    private static final long serialversionuid = -203988976020008362l;
    /**
     * 儿子id
     */
    private long sid;
    /**
     * 儿子姓名
     */
    private string sname;
    /**
     * 该儿子父亲id
     */
    private long fid;
    /**
     * 该儿子父亲信息
     */
    private father father;
}
  1. 联合查询
编写接口

com.lihaozhe.mapper.sonmapper

package com.lihaozhe.mapper;
import com.lihaozhe.vo.sonvo;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/10 下午3:01
 */
public interface sonmapper {
    /**
     * 根据儿子id查询儿子和该儿子父亲的信息
     *
     * @param sid
     * @return
     */
    sonvo selectsonvobysid(@param("sid") long sid);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/sonmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.sonmapper">
    
    <resultmap id="sonvomap" type="sonvo">
        <id property="sid" column="s_id"/>
        <result property="sname" column="s_name"/>
        <result property="fid" column="fid"/>
        <association property="father">
            <id property="fid" column="fid"/>
            <result property="fname" column="f_name"/>
        association>
    resultmap>
    <select id="selectsonvobysid" resultmap="sonvomap">
        select s_id, s_name, s.f_id as fid, f_name
        from son s
                 inner join father f on s.f_id = f.f_id and s_id = #{sid}
    select>
mapper>
编写测试类

com.lihaozhe.mapper.sonmappertest

package com.lihaozhe.mapper;
import com.lihaozhe.util.mybatis.mybatisutil;
import com.lihaozhe.vo.sonvo;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/10 下午3:13
 */
public class sonmappertest {
    @test
    public void selectsonvobysid() {
        sqlsession sqlsession = mybatisutil.opensqlsession();
        sonmapper mapper = sqlsession.getmapper(sonmapper.class);
        sonvo sonvo = mapper.selectsonvobysid(3l);
        mybatisutil.close();
        system.out.println(sonvo);
    }
}
  1. 子查询
编写接口

com.lihaozhe.mapper.fathermapper

package com.lihaozhe.mapper;
import com.lihaozhe.vo.fathervo;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/10 上午11:15
 */
public interface fathermapper {
    /**
     * 根据父亲id获取父亲信息
     *
     * @param fid
     * @return
     */
    father selectfatherbyid(@param("fid") long fid);
}

com.lihaozhe.mapper.sonmapper

package com.lihaozhe.mapper;
import com.lihaozhe.vo.sonvo;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/10 上午11:08
 */
public interface sonmapper {
    /**
     * 根据儿子id查询儿子和该儿子父亲的信息
     *
     * @param sid
     * @return
     */
    sonvo selectsonvobyid(@param("sid") long sid);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/fathermapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.fathermapper">
    
    <select id="selectfatherbyid" resulttype="father">
        select *
        from `father`
        where `f_id` = #{fid}
    select>
mapper>

src/main/resources/com/lihaozhe/mapper/sonmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.sonmapper">
    
    <resultmap id="sonvomapper" type="sonvo">
        <id property="sid" column="s_id"/>
        <result property="sname" column="s_name"/>
        <result property="fid" column="f_id"/>
        <association property="father" column="f_id" select="com.lihaozhe.mapper.fathermapper.selectfatherbyid"/>
    resultmap>
    <select id="selectsonvobyid" resultmap="sonvomapper">
        select *
        from `son`
        where `s_id` = #{sid}
    select>
mapper>
编写测试类

com.lihaozhe.mapper.fathermappertest

package com.lihaozhe.mapper;
import com.lihaozhe.util.mybatis.mybatisutil;
import com.lihaozhe.vo.fathervo;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/10 上午11:22
 */
public class fathermappertest {
    @test
    public void selectfatherbyid(){
        sqlsession sqlsession = mybatisutil.opensqlsession();
        fathermapper mapper = sqlsession.getmapper(fathermapper.class);
        father father = mapper.selectfatherbyid(1l);
        mybatisutil.close();
        system.out.println(father);
    }
}

com.lihaozhe.mapper.sonmappertest

package com.lihaozhe.mapper;
import com.lihaozhe.util.mybatis.mybatisutil;
import com.lihaozhe.vo.sonvo;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/10 上午11:33
 */
public class sonmappertest {
    @test
    public void selectsonvobyid() {
        sqlsession sqlsession = mybatisutil.opensqlsession();
        sonmapper mapper = sqlsession.getmapper(sonmapper.class);
        sonvo sonvo = mapper.selectsonvobyid(3l);
        mybatisutil.close();
        system.out.println(sonvo);
    }
}

解析sql

==>  preparing: select s_id, s_name,f_id from son where s_id = ?
==> parameters: 1(long)
<==    columns: s_id, s_name, f_id
<==        row: 1, 李金吒, 1
====>  preparing: select f_id, f_name from father where f_id = ?
====> parameters: 1(integer)
<====    columns: f_id, f_name
<====        row: 1, 李靖
<====      total: 1
<==      total: 1

一对多

下面的案例使用子查询和联合查询分别实现

编写vo类

com.lihaozhe.vo.fathervo

package com.lihaozhe.vo;
import com.lihaozhe.pojo.son;
import lombok.allargsconstructor;
import lombok.data;
import lombok.noargsconstructor;
import java.io.serializable;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/14 上午10:27
 */
@data
@noargsconstructor
@allargsconstructor
public class fathervo implements serializable {
    private static final long serialversionuid = -1335512987974717220l;
    /**
     * 父亲id
     */
    private long fid;
    /**
     * 父亲姓名
     */
    private string fname;
    /**
     * 该父亲的儿子们
     */
    private list<son> sons;
}
  1. 子查询
编写接口

com.lihaozhe.mapper.sonmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.son;
import com.lihaozhe.vo.sonvo;
import org.apache.ibatis.annotations.param;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/10 上午11:08
 */
public interface sonmapper {
    /**
     * 根据父亲id获取该父亲的儿子列表
     * @param fid
     * @return
     */
    list<son> selectallbyfid(@param("fid") long fid);
}

com.lihaozhe.mapper.fathermapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.father;
import com.lihaozhe.vo.fathervo;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/10 上午11:15
 */
public interface fathermapper {
    /**
     * 根据父亲id获取父亲及其儿子们的信息
     *
     * @param fid
     * @return
     */
    fathervo selectfathervobyid(@param("fid") long fid);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/sonmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.sonmapper">
    
    <select id="selectallbyfid" resulttype="son">
        select *
        from son
        where f_id = #{fid};
    select>
mapper>

src/main/resources/com/lihaozhe/mapper/fathermapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.fathermapper">
    
    <resultmap id="fathervomap" type="fathervo">
        <id property="fid" column="f_id"/>
        <result property="fname" column="f_name"/>
        <collection property="sons" oftype="son" column="f_id" select="com.lihaozhe.mapper.sonmapper.selectallbyfid"/>
    resultmap>
    <select id="selectfathervobyid" resultmap="fathervomap">
        select *
        from father
        where f_id = #{fid};
    select>
mapper>
编写测试类

com.lihaozhe.mapper.sonmappertest

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.son;
import com.lihaozhe.util.mybatis.mybatisutil;
import com.lihaozhe.vo.sonvo;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/10 上午11:33
 */
public class sonmappertest {
    @test
    public void selectallbyfid(){
        sqlsession sqlsession = mybatisutil.opensqlsession();
        sonmapper mapper = sqlsession.getmapper(sonmapper.class);
        list<son> sons = mapper.selectallbyfid(1l);
        mybatisutil.close();
        sons.foreach(system.out::println);
    }
}

com.lihaozhe.mapper.fathermappertest

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.father;
import com.lihaozhe.util.mybatis.mybatisutil;
import com.lihaozhe.vo.fathervo;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/10 上午11:22
 */
public class fathermappertest {
    @test
    public void selectfathervobyid(){
        sqlsession sqlsession = mybatisutil.opensqlsession();
        fathermapper mapper = sqlsession.getmapper(fathermapper.class);
        fathervo fathervo = mapper.selectfathervobyid(1l);
        mybatisutil.close();
        system.out.println(fathervo);
    }
}

解析sql

==>  preparing: select f_id, f_name from father where f_id = ?
==> parameters: 1(long)
<==    columns: f_id, f_name
<==        row: 1, 李靖
====>  preparing: select s_id, s_name,f_id from son where f_id = ?
====> parameters: 1(integer)
<====    columns: s_id, s_name, f_id
<====        row: 1, 李金吒, 1
<====        row: 2, 李木吒, 1
<====        row: 3, 李哪吒, 1
<====      total: 3
<==      total: 1
  1. 联合查询用例
编写接口

com.lihaozhe.mapper.fathermapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.father;
import com.lihaozhe.vo.fathervo;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/10 下午3:49
 */
public interface fathermapper {
    /**
     * 根据父亲id获取父亲及其儿子们的信息
     *
     * @param fid
     * @return
     */
    fathervo selectfathervobysid(@param("fid") long fid);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/fathermapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.fathermapper">
    
    <resultmap id="fathervomapper" type="fathervo">
        <id property="fid" column="fid"/>
        <result property="fname" column="f_name"/>
        <collection property="sons" oftype="son">
            <id property="sid" column="s_id"/>
            <result property="sname" column="s_name"/>
            <result property="fid" column="fid"/>
        collection>
    resultmap>
    <select id="selectfathervobysid" resultmap="fathervomapper">
        select f.f_id as fid, f_name, s_id, s_name
        from father f
                 inner join son s on f.f_id = s.f_id and f.f_id = #{fid}
    select>
mapper>
编写测试类

com.lihaozhe.mapper.fathermappertest

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.father;
import com.lihaozhe.util.mybatis.mybatisutil;
import com.lihaozhe.vo.fathervo;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/10 下午3:52
 */
public class fathermappertest {
    @test
    public void selectfathervobysid(){
        sqlsession sqlsession = mybatisutil.opensqlsession();
        fathermapper mapper = sqlsession.getmapper(fathermapper.class);
        fathervo fathervo = mapper.selectfathervobysid(1l);
        mybatisutil.close();
        system.out.println(fathervo);
    }
}

多对多

  • 直接多对多
  • 间接多对多 将多对多拆成两个一对多 或 两个多对一
直接多对多

需求:查找某图书类目下的所有图书信息

编写vo类

com.lihaozhe.vo.categoryvo

package com.lihaozhe.vo;
import com.lihaozhe.pojo.book;
import lombok.allargsconstructor;
import lombok.data;
import lombok.noargsconstructor;
import java.io.serializable;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/14 上午11:27
 */
@data
@noargsconstructor
@allargsconstructor
public class categoryvo implements serializable {
    private static final long serialversionuid = 5565769402064534797l;
    /**
     * 分类id
     */
    private long cid;
    /**
     * 分类名称
     */
    private string cname;
    /**
     * 某分类的图书列表
     */
    private list<book> books;
}
编写接口

com.lihaozhe.mapper.categorymapper

package com.lihaozhe.mapper;
import com.lihaozhe.vo.categoryvo;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/14 上午11:28
 */
public interface categorymapper {
    /**
     * 根据分类id获取分类及其分类下的图书列表
     *
     * @param cid
     * @return
     */
    categoryvo selectcategoryvobycid(@param("cid") long cid);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/categorymapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.categorymapper">
    
    <resultmap id="categoryvomap" type="categoryvo">
        <id property="cid" column="cid"/>
        <id property="cname" column="cname"/>
        <collection property="books" oftype="book">
            <id property="bid" column="bid"/>
            <result property="bname" column="bname"/>
        collection>
    resultmap>
    <select id="selectcategoryvobycid" resultmap="categoryvomap">
        select cid, cname, bid, bname
        from category
                 inner join book_category
                 inner join book
                            on cid = m_cid and bid = m_bid and cid = #{cid}
    select>
mapper>
编写测试类

com.lihaozhe.mapper.categorymappertest

package com.lihaozhe.mapper;
import com.lihaozhe.util.mybatis.mybatisutil;
import com.lihaozhe.vo.categoryvo;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/14 上午11:34
 */
public class categorymappertest {
    @test
    public void selectcategoryvobycid(){
        sqlsession sqlsession = mybatisutil.opensqlsession();
        categorymapper mapper = sqlsession.getmapper(categorymapper.class);
        categoryvo categoryvo = mapper.selectcategoryvobycid(3l);
        mybatisutil.close();
        system.out.println(categoryvo);
    }
}

需求:查找某图书的分类信息

编写vo类

com.lihaozhe.vo.bookvo

package com.lihaozhe.vo;
import com.lihaozhe.pojo.category;
import lombok.allargsconstructor;
import lombok.data;
import lombok.noargsconstructor;
import java.io.serializable;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/14 上午11:36
 */
@data
@noargsconstructor
@allargsconstructor
public class bookvo implements serializable {
    private static final long serialversionuid = 6785352134653400094l;
    /**
     * 书的id
     */
    private long bid;
    /**
     * 书名
     */
    private string bname;
    /**
     * 某图书的分类信息列表
     */
    private list<category> categories;
}
编写接口

com.lihaozhe.mapper.bookmapper

package com.lihaozhe.mapper;
import com.lihaozhe.vo.bookvo;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/14 上午11:38
 */
public interface bookmapper {
    /**
     * 根据图书id查询图书信息包括该图书的分类信息
     *
     * @param bid
     * @return
     */
    bookvo selectbookvobybid(@param("bid") long bid);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/bookmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.bookmapper">
    
    <resultmap id="bookvomap" type="bookvo">
        <id property="bid" column="bid"/>
        <result property="bname" column="bname"/>
        <collection property="categories" oftype="category">
            <id property="cid" column="cid"/>
            <id property="cname" column="cname"/>
        collection>
    resultmap>
    <select id="selectbookvobybid" resultmap="bookvomap">
        select bid, bname, cid, cname
        from book
                 inner join book_category
                 inner join category
                            on bid = m_bid and cid = m_cid and bid = #{bid}
    select>
mapper>
编写测试类
package com.lihaozhe.mapper;
import com.lihaozhe.util.mybatis.mybatisutil;
import com.lihaozhe.vo.bookvo;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/14 上午11:34
 */
public class bookmappertest {
    @test
    public void test(){
        sqlsession sqlsession = mybatisutil.opensqlsession();
        bookmapper mapper = sqlsession.getmapper(bookmapper.class);
        bookvo bookvo = mapper.selectbookvobybid(3l);
        mybatisutil.close();
        system.out.println(bookvo);
    }
}
间接多对多
编写中间表映射类

com.lihaozhe.pojo.studentcourse

package com.lihaozhe.pojo;
import lombok.allargsconstructor;
import lombok.data;
import lombok.noargsconstructor;
import java.io.serializable;
@data
@noargsconstructor
@allargsconstructor
public class studentcourse implements serializable {
    private static final long serialversionuid = 7294808647412902387l;
    /**
     * 学生id
     */
    private long sid;
    /**
     * 课程id
     */
    private long cid;
    /**
     * 学生信息
     */
    private student student;
    /**
     * 课程信息
     */
    private course course;
}
编写接口

com.lihaozhe.mapper.coursemapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.course;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/11 下午3:04
 */
public interface coursemapper {
    /**
     * 根据课程id查找课程
     *
     * @param cid
     * @return
     */
    course selectcoursebycid(@param("cid") long cid);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/coursemapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.coursemapper">
    
    <select id="selectcoursebycid" resulttype="course">
        select *
        from `course`
        where `c_id` = #{cid}
    select>
mapper>
编写测试类

com.lihaozhe.mapper.coursemappertest

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.course;
import com.lihaozhe.util.mybatis.mybatisutil;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/11 下午3:06
 */
public class coursemappertest {
    @test
    public void selectcoursebycid(){
        sqlsession sqlsession = mybatisutil.opensqlsession();
        coursemapper mapper = sqlsession.getmapper(coursemapper.class);
        course course = mapper.selectcoursebycid(3l);
        mybatisutil.close();
        system.out.println(course);
    }
}
编写接口

com.lihaozhe.mapper.studentmapper

package com.lihaozhe.mapper;
import com.lihaozhe.vo.studentvo;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/11 下午3:08
 */
public interface studentmapper {
    /**
     * 根据学生id 查询学生信息 包含所需课程的id列表
     *
     * @param sid
     * @return
     */
    studentvo selectstudentvobysid(@param("sid") long sid);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/studentmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.studentmapper">
    
    <resultmap id="studentvomap" type="studentvo">
        <id property="sid" column="sid"/>
        <result property="sname" column="s_name"/>
        <collection property="studentcourses" oftype="studentcourse">
            <result property="sid" column="sid"/>
            <result property="cid" column="c_id"/>
            <association property="course" column="c_id" select="com.lihaozhe.mapper.coursemapper.selectcoursebycid"/>
        collection>
    resultmap>
    <select id="selectstudentvobysid" resultmap="studentvomap">
        select stu.s_id as sid, s_name, c_id
        from student as stu
                 inner join student_course sc on stu.s_id = sc.s_id and stu.s_id = #{sid}
    select>
mapper>
编写测试类

com.lihaozhe.mapper.studentmappertest

package com.lihaozhe.mapper;
import com.lihaozhe.util.mybatis.mybatisutil;
import com.lihaozhe.vo.studentvo;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/11 下午3:23
 */
public class studentmappertest {
    @test
    public void selectstudentvobysid() {
        sqlsession sqlsession = mybatisutil.opensqlsession();
        studentmapper mapper = sqlsession.getmapper(studentmapper.class);
        studentvo studentvo = mapper.selectstudentvobysid(3l);
        system.out.println(studentvo);
        system.out.println(studentvo.getsname());
        studentvo.getstudentcourses().foreach(studentcourse -> system.out.println(studentcourse.getcourse()));
    }
}
sql解析
==>  preparing: select s.s_id, s_name, c_id from `student` s inner join `student_course` sc on s.s_id = sc.s_id and s.s_id = ?
==> parameters: 1(long)
<==    columns: s_id, s_name, c_id
<==        row: 1, stu01, 1
====>  preparing: select * from `course` where `c_id` = ?
====> parameters: 1(integer)
<====    columns: c_id, c_name
<====        row: 1, java
<====      total: 1
<==        row: 1, stu01, 2
====>  preparing: select * from `course` where `c_id` = ?
====> parameters: 2(integer)
<====    columns: c_id, c_name
<====        row: 2, scala
<====      total: 1
<==      total: 2
编写接口

com.lihaozhe.mapper.studentmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.student;
import com.lihaozhe.vo.studentvo;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/11 下午3:08
 */
public interface studentmapper {
    /**
     * 根据学生id 查询学生信息 包含所需课程的id列表
     *
     * @param sid
     * @return
     */
    studentvo selectstudentvobysid(@param("sid") long sid);
    /**
     * 根据学生id 查询学生信息
     *
     * @param sid
     * @return
     */
    student selectstudentbysid(@param("sid") long sid);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/studentmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.studentmapper">
    
    <resultmap id="studentvomap" type="studentvo">
        <id property="sid" column="sid"/>
        <result property="sname" column="s_name"/>
        <collection property="studentcourses" oftype="studentcourse">
            <result property="sid" column="sid"/>
            <result property="cid" column="c_id"/>
            <association property="course" column="c_id" select="com.lihaozhe.mapper.coursemapper.selectcoursebycid"/>
        collection>
    resultmap>
    <select id="selectstudentvobysid" resultmap="studentvomap">
        select stu.s_id as sid, s_name, c_id
        from student as stu
                 inner join student_course sc on stu.s_id = sc.s_id and stu.s_id = #{sid}
    select>
    
    <select id="selectstudentbysid" resulttype="student">
        select * from `student` where `s_id` = #{sid}
    select>
mapper>
编写测试类

com.lihaozhe.mapper.studentmappertest

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.student;
import com.lihaozhe.util.mybatis.mybatisutil;
import com.lihaozhe.vo.studentvo;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/11 下午3:23
 */
public class studentmappertest {
     @test
    public void selectstudentvobysid() {
        sqlsession sqlsession = mybatisutil.opensqlsession();
        studentmapper mapper = sqlsession.getmapper(studentmapper.class);
        studentvo studentvo = mapper.selectstudentvobysid(3l);
        system.out.println(studentvo);
        system.out.println(studentvo.getsname());
        studentvo.getstudentcourses().foreach(studentcourse -> system.out.println(studentcourse.getcourse()));
    }
    @test
    public void selectstudentbysid() {
        sqlsession sqlsession = mybatisutil.opensqlsession();
        studentmapper mapper = sqlsession.getmapper(studentmapper.class);
        student student = mapper.selectstudentbysid(3l);
        system.out.println(student);
    }
}
编写vo类

com.lihaozhe.vo.coursevo

package com.lihaozhe.vo;
import com.lihaozhe.pojo.studentcourse;
import lombok.allargsconstructor;
import lombok.data;
import lombok.noargsconstructor;
import java.io.serializable;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/14 下午12:22
 */
@data
@noargsconstructor
@allargsconstructor
public class coursevo implements serializable {
    private static final long serialversionuid = -2649136027724661116l;
    /**
     * 课程id
     */
    private long cid;
    /**
     * 课程名称
     */
    private string cname;
    /**
     * 课程关联信息
     */
    private list<studentcourse> studentcourses;
}
编写接口

com.lihaozhe.mapper.coursemapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.course;
import com.lihaozhe.vo.coursevo;
import org.apache.ibatis.annotations.param;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/11 下午3:04
 */
public interface coursemapper {
    /**
     * 根据课程id查找课程
     *
     * @param cid
     * @return
     */
    course selectcoursebycid(@param("cid") long cid);
    /**
     * 根据课程id查找课程 包含所需课程的id列表
     *
     * @param cid
     * @return
     */
    coursevo selectcoursevobycid(@param("cid") long cid);
}
编写映射配置文件

src/main/resources/com/lihaozhe/mapper/coursemapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.coursemapper">
    
    <select id="selectcoursebycid" resulttype="course">
        select *
        from `course`
        where `c_id` = #{cid}
    select>
    
    <resultmap id="coursevomap" type="coursevo">
        <id property="cid" column="cid"/>
        <result property="cname" column="c_name"/>
        <collection property="studentcourses" oftype="studentcourse">
            <result property="sid" column="sid"/>
            <result property="cid" column="c_id"/>
            <association property="student" column="s_id" select="com.lihaozhe.mapper.studentmapper.selectstudentbysid"/>
        collection>
    resultmap>
    <select id="selectcoursevobycid" resultmap="coursevomap">
        select c.c_id as cid, c_name, s_id
        from course as c
                 inner join student_course sc on c.c_id = sc.c_id and c.c_id = #{cid}
    select>
mapper>
编写测试类

com.lihaozhe.mapper.coursemappertest

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.course;
import com.lihaozhe.util.mybatis.mybatisutil;
import com.lihaozhe.vo.coursevo;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/11 下午3:06
 */
public class coursemappertest {
    @test
    public void selectcoursebycid(){
        sqlsession sqlsession = mybatisutil.opensqlsession();
        coursemapper mapper = sqlsession.getmapper(coursemapper.class);
        course course = mapper.selectcoursebycid(3l);
        mybatisutil.close();
        system.out.println(course);
    }
    @test
    public void selectcoursevobycid(){
        sqlsession sqlsession = mybatisutil.opensqlsession();
        coursemapper mapper = sqlsession.getmapper(coursemapper.class);
        coursevo coursevo = mapper.selectcoursevobycid(3l);
        system.out.println(coursevo);
        system.out.println(coursevo.getcname());
        coursevo.getstudentcourses().foreach(studentcourse -> system.out.println(studentcourse.getstudent()));
    }
}

延迟加载

@test
public void selectstudentvobysid01() {
    sqlsession sqlsession = mybatisutil.getsqlsession();
    studentmapper mapper = sqlsession.getmapper(studentmapper.class);
    studentvo studentvo = mapper.selectstudentvobysid(1l);
    mybatisutil.close();
    system.out.println(studentvo.getsname());
}
opening jdbc connection
created connection 379121284.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@1698ee84]
==>  preparing: select s.s_id, s_name, c_id from `student` s inner join `student_course` sc on s.s_id = sc.s_id and s.s_id = ?
==> parameters: 1(long)
<==    columns: s_id, s_name, c_id
<==        row: 1, stu01, 1
====>  preparing: select * from `course` where `c_id` = ?
====> parameters: 1(integer)
<====    columns: c_id, c_name
<====        row: 1, java
<====      total: 1
<==        row: 1, stu01, 2
====>  preparing: select * from `course` where `c_id` = ?
====> parameters: 2(integer)
<====    columns: c_id, c_name
<====        row: 2, scala
<====      total: 1
<==      total: 2
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@1698ee84]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@1698ee84]
returned connection 379121284 to pool.
@test
public void selectstudentvobysid02() {
    sqlsession sqlsession = mybatisutil.getsqlsession();
    studentmapper mapper = sqlsession.getmapper(studentmapper.class);
    studentvo studentvo = mapper.selectstudentvobysid(1l);
    mybatisutil.close();
    studentvo.getstudentcourses().foreach(studentcourse -> system.out.println(studentcourse.getcourse()));
}
opening jdbc connection
created connection 379121284.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@1698ee84]
==>  preparing: select s.s_id, s_name, c_id from `student` s inner join `student_course` sc on s.s_id = sc.s_id and s.s_id = ?
==> parameters: 1(long)
<==    columns: s_id, s_name, c_id
<==        row: 1, stu01, 1
====>  preparing: select * from `course` where `c_id` = ?
====> parameters: 1(integer)
<====    columns: c_id, c_name
<====        row: 1, java
<====      total: 1
<==        row: 1, stu01, 2
====>  preparing: select * from `course` where `c_id` = ?
====> parameters: 2(integer)
<====    columns: c_id, c_name
<====        row: 2, scala
<====      total: 1
<==      total: 2
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@1698ee84]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@1698ee84]
returned connection 379121284 to pool.
course(cid=1, cname=java)
course(cid=2, cname=scala)
process finished with exit code 0

从上面第一个案例可以看出客户只想查看学生休息并不想看学生所学专业信息 但是 仍然执行了子查询,

我们希望 当想看该学生和该学生所学专业详细信息的之后才走子查询而只看学生信息的时候不走子查询

于是我们开启了延迟加载

核心配置文件


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

@test
public void selectstudentvobysid01() {
    sqlsession sqlsession = mybatisutil.getsqlsession();
    studentmapper mapper = sqlsession.getmapper(studentmapper.class);
    studentvo studentvo = mapper.selectstudentvobysid(1l);
    mybatisutil.close();
    system.out.println(studentvo.getsname());
}
opening jdbc connection
created connection 379121284.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@1698ee84]
==>  preparing: select s.s_id, s_name, c_id from `student` s inner join `student_course` sc on s.s_id = sc.s_id and s.s_id = ?
==> parameters: 1(long)
<==    columns: s_id, s_name, c_id
<==        row: 1, stu01, 1
<==        row: 1, stu01, 2
<==      total: 2
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@1698ee84]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@1698ee84]
returned connection 379121284 to pool.
@test
public void selectstudentvobysid02() {
    sqlsession sqlsession = mybatisutil.getsqlsession();
    studentmapper mapper = sqlsession.getmapper(studentmapper.class);
    studentvo studentvo = mapper.selectstudentvobysid(1l);
    mybatisutil.close();
    studentvo.getstudentcourses().foreach(studentcourse -> system.out.println(studentcourse.getcourse()));
}
opening jdbc connection
created connection 544966217.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@207b8649]
==>  preparing: select s.s_id, s_name, c_id from `student` s inner join `student_course` sc on s.s_id = sc.s_id and s.s_id = ?
==> parameters: 1(long)
<==    columns: s_id, s_name, c_id
<==        row: 1, stu01, 1
<==        row: 1, stu01, 2
<==      total: 2
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@207b8649]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@207b8649]
returned connection 544966217 to pool.
opening jdbc connection
checked out connection 544966217 from pool.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@207b8649]
==>  preparing: select * from `course` where `c_id` = ?
==> parameters: 1(integer)
<==    columns: c_id, c_name
<==        row: 1, java
<==      total: 1
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@207b8649]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@207b8649]
returned connection 544966217 to pool.
course(cid=1, cname=java)
opening jdbc connection
checked out connection 544966217 from pool.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@207b8649]
==>  preparing: select * from `course` where `c_id` = ?
==> parameters: 2(integer)
<==    columns: c_id, c_name
<==        row: 2, scala
<==      total: 1
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@207b8649]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@207b8649]
returned connection 544966217 to pool.
course(cid=2, cname=scala)
process finished with exit code 0

侵入式延迟 积极加载

侵入式延迟 访问主对象及主对象里面的属性时,不光会加载主对象(即从数据库中查询主对象的信息),还会一同加载关联对象。 积极加载

深度延迟 访问主对象属性时,只加载主,只有当访问关联对象的属性时,才会去加载关联对象。 按需加载

<settings>
    
    <setting name="mapunderscoretocamelcase" value="true"/>
    
    <setting name="logimpl" value="stdout_logging"/>
    
    
    <setting name="lazyloadingenabled" value="true"/>
    
    
    
    
    
settings>

映射配置文件中子查询设置fetchtype

  • fetchtype=“eager” 不支持懒加载

  • fetchtype=“lzsy” 支持懒加载

@test
public void selectdeptvobyid01() {
    // 获取接口代理对象
    deptmapper mapper = sqlsession.getmapper(deptmapper.class);
    // 执行代理对象中方法
    mapper.selectdeptvobyid(3l);
    // 释放资源
    sqlsession.close();
}
@test
public void selectdeptvobyid02() {
    // 获取接口代理对象
    deptmapper mapper = sqlsession.getmapper(deptmapper.class);
    // 执行代理对象中方法
    deptvo deptvo = mapper.selectdeptvobyid(3l);
    // 释放资源
    sqlsession.close();
    system.out.println(deptvo.getdname());
}
@test
public void selectdeptvobyid03() {
    // 获取接口代理对象
    deptmapper mapper = sqlsession.getmapper(deptmapper.class);
    // 执行代理对象中方法
    deptvo deptvo = mapper.selectdeptvobyid(3l);
    // 释放资源
    sqlsession.close();
    deptvo.getemps();
}

一级缓存

编写测试类

com.lihaozhe.mapper.cachetest

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import com.lihaozhe.util.mybatis.mybatisutil;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/12 上午10:05
 */
public class cachetest {
    @test
    public void testcache01(){
        sqlsession sqlsession = mybatisutil.getsqlsession();
        personmapper mapper = sqlsession.getmapper(personmapper.class);
        person person01 = mapper.selectbyid(3l);
        person person02 = mapper.selectbyid(3l);
        mybatisutil.close();
    }
}
opening jdbc connection
created connection 1552870927.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
==>  preparing: select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `id` = ?
==> parameters: 3(long)
<==    columns: id, uuid, mobile, nickname, id_card
<==        row: 3, 5ee0074d47064285b8c5925534d70d84, 17674856547, 令狐荡, 649152199504171242
<==      total: 1
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
returned connection 1552870927 to pool.
package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import com.lihaozhe.util.mybatis.mybatisutil;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/12 上午10:05
 */
public class cachetest {
    @test
    public void testcache02() {
        sqlsession sqlsession = mybatisutil.opensqlsession();
        personmapper mapper = sqlsession.getmapper(personmapper.class);
        person person01 = mapper.selectbyid(6l);
        person person02 = mapper.selectbyid(3l);
        mybatisutil.close();
    }0
}
opening jdbc connection
created connection 1552870927.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
==>  preparing: select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `id` = ?
==> parameters: 6(long)
<==    columns: id, uuid, mobile, nickname, id_card
<==        row: 6, aebe1bd701b24fb89347c78bb3aaf938, 13651227685, 欧阳脓, 644102199803081660
<==      total: 1
==>  preparing: select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `id` = ?
==> parameters: 3(long)
<==    columns: id, uuid, mobile, nickname, id_card
<==        row: 3, 5ee0074d47064285b8c5925534d70d84, 17674856547, 令狐荡, 649152199504171242
<==      total: 1
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
returned connection 1552870927 to pool.
package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import com.lihaozhe.util.mybatis.mybatisutil;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/12 上午10:05
 */
public class cachetest {
    @test
    public void testcache03() {
        sqlsession sqlsession = mybatisutil.opensqlsession();
        personmapper mapper01 = sqlsession.getmapper(personmapper.class);
        personmapper mapper02 = sqlsession.getmapper(personmapper.class);
        person person01 = mapper01.selectbyid(3l);
        person person02 = mapper02.selectbyid(3l);
        mybatisutil.close();
    }
}
opening jdbc connection
created connection 1552870927.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
==>  preparing: select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `id` = ?
==> parameters: 3(long)
<==    columns: id, uuid, mobile, nickname, id_card
<==        row: 3, 5ee0074d47064285b8c5925534d70d84, 17674856547, 令狐荡, 649152199504171242
<==      total: 1
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
returned connection 1552870927 to pool.
package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import com.lihaozhe.util.mybatis.mybatisutil;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/12 上午10:05
 */
public class cachetest {
    @test
    public void testcache04() {
        sqlsession sqlsession01 = mybatisutil.getsqlsession();
        personmapper mapper01 = sqlsession01.getmapper(personmapper.class);
        person person01 = mapper01.selectbyid(3l);
        sqlsession sqlsession02 = mybatisutil.getsqlsession();
        personmapper mapper02 = sqlsession02.getmapper(personmapper.class);
        person person02 = mapper02.selectbyid(3l);
        mybatisutil.close();
    }
}
opening jdbc connection
created connection 1552870927.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
==>  preparing: select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `id` = ?
==> parameters: 3(long)
<==    columns: id, uuid, mobile, nickname, id_card
<==        row: 3, 5ee0074d47064285b8c5925534d70d84, 17674856547, 令狐荡, 649152199504171242
<==      total: 1
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
returned connection 1552870927 to pool.
package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import com.lihaozhe.util.mybatis.mybatisutil;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/12 上午10:05
 */
public class cachetest {
    @test
    public void testcache05() {
        sqlsession sqlsession01 = mybatisutil.getsqlsession();
        personmapper mapper01 = sqlsession01.getmapper(personmapper.class);
        person person01 = mapper01.selectbyid(3l);
        mybatisutil.close();
        
        sqlsession sqlsession02 = mybatisutil.getsqlsession();
        personmapper mapper02 = sqlsession02.getmapper(personmapper.class);
        person person02 = mapper02.selectbyid(3l);
        mybatisutil.close();
    }
}
opening jdbc connection
created connection 1552870927.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
==>  preparing: select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `id` = ?
==> parameters: 3(long)
<==    columns: id, uuid, mobile, nickname, id_card
<==        row: 3, 5ee0074d47064285b8c5925534d70d84, 17674856547, 令狐荡, 649152199504171242
<==      total: 1
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
returned connection 1552870927 to pool.
opening jdbc connection
checked out connection 1552870927 from pool.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
==>  preparing: select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `id` = ?
==> parameters: 3(long)
<==    columns: id, uuid, mobile, nickname, id_card
<==        row: 3, 5ee0074d47064285b8c5925534d70d84, 17674856547, 令狐荡, 649152199504171242
<==      total: 1
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@5c8eee0f]
returned connection 1552870927 to pool.

结论:mybatis一级缓存默认开启,同一个sqlsession中查询条件一致则走一级缓存,一级缓存不能跨sqlsession

二级缓存

mybatis如果想跨sqlsession缓存则可以采用将查询结果缓存至第三方,例如:

  • ehcache
  • memcached
  • redis

开启二级缓存步骤

maven项目提前在pom.xml文件中增加相关依赖

  1. 在核心配置文件中加入
<settings>
		<setting name="cacheenabled" value="true" />
settings>
  1. 在映射配置文件中加入
    回收策略:
    lru – 最近最少使用的:移除最长时间不被使用的对象。
    fifo – 先进先出:按对象进入缓存的顺序来移除它们。
    soft – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
    weak – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
<cache eviction="fifo" flushinterval="60000" size="512" readonly="true" />
  1. 缓存遇到commit失效

  2. ehcache二级缓存在映射配置文件中加入

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

添加maven依赖

<dependency>
    <groupid>org.ehcachegroupid>
    <artifactid>ehcacheartifactid>
    <version>3.9.9version>
dependency>
<dependency>
    <groupid>org.mybatis.cachesgroupid>
    <artifactid>mybatis-ehcacheartifactid>
    <version>1.2.2version>
dependency>

编写核心配置文件

<settings>
	
	<setting name="cacheenabled" value="true" />
settings>

编写映射配置文件

src/main/resources/com/lihaozhe/mapper/personmapper.xml

添加以下内容


<cache eviction="fifo" flushinterval="60000" size="512" readonly="true" />

在需要缓存的查找标签增加设置usecache=true

<select id="selectbyid" resulttype="person" usecache="true">
    <include refid="select_person">include>
    <where>
        `id` = #{id}
    where>
select>

编写测试类

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import com.lihaozhe.util.mybatis.mybatisutil;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/12 上午10:05
 */
public class cachetest {
    @test
    public void testcache05() {
        sqlsession sqlsession01 = mybatisutil.opensqlsession();
        personmapper mapper01 = sqlsession01.getmapper(personmapper.class);
        person person01 = mapper01.selectbyid(3l);
        mybatisutil.close();
        sqlsession sqlsession02 = mybatisutil.opensqlsession();
        personmapper mapper02 = sqlsession02.getmapper(personmapper.class);
        person person02 = mapper02.selectbyid(3l);
        mybatisutil.close();
    }
}
cache hit ratio [com.lihaozhe.mapper.personmapper]: 0.0
opening jdbc connection
created connection 1045731788.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@3e5499cc]
==>  preparing: select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `id` = ?
==> parameters: 3(long)
<==    columns: id, uuid, mobile, nickname, id_card
<==        row: 3, 5ee0074d47064285b8c5925534d70d84, 17674856547, 令狐荡, 649152199504171242
<==      total: 1
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@3e5499cc]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@3e5499cc]
returned connection 1045731788 to pool.
cache hit ratio [com.lihaozhe.mapper.personmapper]: 0.5
package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import com.lihaozhe.util.mybatis.mybatisutil;
import org.apache.ibatis.session.sqlsession;
import org.junit.jupiter.api.test;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/12 上午10:05
 */
public class cachetest {
    @test
    public void testcache05() {
        sqlsession sqlsession01 = mybatisutil.opensqlsession();
        personmapper mapper01 = sqlsession01.getmapper(personmapper.class);
        person person01 = mapper01.selectbyid(3l);
        mybatisutil.close();
        sqlsession sqlsession02 = mybatisutil.opensqlsession();
        personmapper mapper02 = sqlsession02.getmapper(personmapper.class);
        person person02 = mapper02.selectbyid(3l);
        mybatisutil.close();
    }
}
cache hit ratio [com.lihaozhe.mapper.personmapper]: 0.0
opening jdbc connection
created connection 1045731788.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@3e5499cc]
==>  preparing: select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `id` = ?
==> parameters: 6(long)
<==    columns: id, uuid, mobile, nickname, id_card
<==        row: 6, aebe1bd701b24fb89347c78bb3aaf938, 13651227685, 欧阳脓, 644102199803081660
<==      total: 1
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@3e5499cc]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@3e5499cc]
returned connection 1045731788 to pool.
cache hit ratio [com.lihaozhe.mapper.personmapper]: 0.0
opening jdbc connection
checked out connection 1045731788 from pool.
setting autocommit to false on jdbc connection [com.mysql.cj.jdbc.connectionimpl@3e5499cc]
==>  preparing: select `id`, `uuid`, `mobile`, `nickname`, `id_card` from `person` where `id` = ?
==> parameters: 3(long)
<==    columns: id, uuid, mobile, nickname, id_card
<==        row: 3, 5ee0074d47064285b8c5925534d70d84, 17674856547, 令狐荡, 649152199504171242
<==      total: 1
resetting autocommit to true on jdbc connection [com.mysql.cj.jdbc.connectionimpl@3e5499cc]
closing jdbc connection [com.mysql.cj.jdbc.connectionimpl@3e5499cc]
returned connection 1045731788 to pool.

分页插件 pagehelper

引入maven依赖

<dependency>
    <groupid>com.github.pagehelpergroupid>
    <artifactid>pagehelperartifactid>
    <version>5.3.1version>
dependency>

完整pom.xml文件


<project xmlns="http://maven.apache.org/pom/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
         xsi:schemalocation="http://maven.apache.org/pom/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelversion>4.0.0modelversion>
  <groupid>com.lihaozhegroupid>
  <artifactid>mybatisartifactid>
  <version>1.0-snapshotversion>
  <name>mybatisname>
  <packaging>jarpackaging>
  <properties>
    <jdk.version>17jdk.version>
    <maven.compiler.source>17maven.compiler.source>
    <maven.compiler.target>17maven.compiler.target>
    <maven.compiler.compilerversion>17maven.compiler.compilerversion>
    <maven.compiler.encoding>utf-8maven.compiler.encoding>
    <project.build.sourceencoding>utf-8project.build.sourceencoding>
    <project.reporting.outputencoding>utf-8project.reporting.outputencoding>
    <maven.test.failure.ignore>truemaven.test.failure.ignore>
    <maven.test.skip>truemaven.test.skip>
    <junit.version>5.8.2junit.version>
    <fastjson.version>2.0.6fastjson.version>
    <gson.version>2.9.0gson.version>
    <hutool.version>5.8.0.m3hutool.version>
    <jackson.version>2.13.3jackson.version>
    <lombok.version>1.18.24lombok.version>
    <java-testdata.version>1.1.2java-testdata.version>
  properties>
  <dependencies>
    <dependency>
      <groupid>org.junit.jupitergroupid>
      <artifactid>junit-jupiter-apiartifactid>
      <version>${junit.version}version>
      <scope>testscope>
    dependency>
    <dependency>
      <groupid>com.github.binarywanggroupid>
      <artifactid>java-testdata-generatorartifactid>
      <version>${java-testdata.version}version>
    dependency>
    
    
    <dependency>
      <groupid>org.apache.commonsgroupid>
      <artifactid>commons-lang3artifactid>
      <version>3.8.1version>
    dependency>
    
    <dependency>
      <groupid>commons-iogroupid>
      <artifactid>commons-ioartifactid>
      <version>2.11.0version>
    dependency>
    <dependency>
      <groupid>org.junit.jupitergroupid>
      <artifactid>junit-jupiter-engineartifactid>
      <version>${junit.version}version>
      <scope>testscope>
    dependency>
    <dependency>
      <groupid>cn.hutoolgroupid>
      <artifactid>hutool-allartifactid>
      <version>${hutool.version}version>
    dependency>
    <dependency>
      <groupid>org.projectlombokgroupid>
      <artifactid>lombokartifactid>
      <version>${lombok.version}version>
      <scope>providedscope>
    dependency>
    
    
    <dependency>
      <groupid>com.alibabagroupid>
      <artifactid>fastjsonartifactid>
      <version>${fastjson.version}version>
    dependency>
    
    <dependency>
      <groupid>com.google.code.gsongroupid>
      <artifactid>gsonartifactid>
      <version>${gson.version}version>
    dependency>
    
    <dependency>
      <groupid>com.fasterxml.jackson.coregroupid>
      <artifactid>jackson-coreartifactid>
      <version>${jackson.version}version>
    dependency>
    <dependency>
      <groupid>com.fasterxml.jackson.coregroupid>
      <artifactid>jackson-annotationsartifactid>
      <version>${jackson.version}version>
    dependency>
    <dependency>
      <groupid>com.fasterxml.jackson.coregroupid>
      <artifactid>jackson-databindartifactid>
      <version>${jackson.version}version>
    dependency>
    <dependency>
      <groupid>com.fasterxml.jackson.datatypegroupid>
      <artifactid>jackson-datatype-jsr310artifactid>
      <version>${jackson.version}version>
    dependency>
    <dependency>
      <groupid>mysqlgroupid>
      <artifactid>mysql-connector-javaartifactid>
      <version>8.0.29version>
    dependency>
    <dependency>
      <groupid>org.mybatisgroupid>
      <artifactid>mybatisartifactid>
      <version>3.5.10version>
    dependency>
    <dependency>
      <groupid>com.alibabagroupid>
      <artifactid>druidartifactid>
      <version>1.2.8version>
    dependency>
    <dependency>
      <groupid>org.ehcachegroupid>
      <artifactid>ehcacheartifactid>
      <version>3.9.9version>
    dependency>
    <dependency>
      <groupid>org.mybatis.cachesgroupid>
      <artifactid>mybatis-ehcacheartifactid>
      <version>1.2.2version>
    dependency>
    <dependency>
      <groupid>com.github.pagehelpergroupid>
      <artifactid>pagehelperartifactid>
      <version>5.3.1version>
    dependency>
    <dependency>
      <groupid>org.springframeworkgroupid>
      <artifactid>spring-contextartifactid>
      <version>5.3.20version>
    dependency>
  dependencies>
  <build>
    
    
    <plugins>
      <plugin>
        <groupid>org.apache.maven.pluginsgroupid>
        <artifactid>maven-war-pluginartifactid>
        <version>3.3.2version>
      plugin>
      
      <plugin>
        <groupid>org.apache.maven.pluginsgroupid>
        <artifactid>maven-compiler-pluginartifactid>
        <version>3.8.1version>
        <configuration>
          
          <encoding>utf-8encoding>
          
          <source>${jdk.version}source>
          <target>${jdk.version}target>
        configuration>
      plugin>
      <plugin>
        <groupid>org.apache.maven.pluginsgroupid>
        <artifactid>maven-clean-pluginartifactid>
        <version>3.2.0version>
      plugin>
      <plugin>
        <groupid>org.apache.maven.pluginsgroupid>
        <artifactid>maven-resources-pluginartifactid>
        <version>3.2.0version>
      plugin>
      
      <plugin>
        <groupid>org.apache.maven.pluginsgroupid>
        <artifactid>maven-surefire-pluginartifactid>
        <version>2.22.2version>
        <configuration>
          <skip>trueskip>
        configuration>
      plugin>
    plugins>
  build>
project>

编写核心配置文件

追加以下内容

<plugins>
    
    <plugin interceptor="com.github.pagehelper.pageinterceptor">
        
        <property name="helperdialect" value="mysql"/>
        
        <property name="pagesizezero" value="true"/>
        
        <property name="reasonable" value="true" />
    plugin>
plugins>

page参数详解

1. helperdialect :分页插件会自动检测当前的数据库链接,自动选择合适的分页方式。 你可以配置 helperdialect 属性来指定分页插件使用哪种方言。配置时,可以使用下面的缩写值:oracle , mysql , mariadb , sqlite , hsqldb , postgresql , db2 , sqlserver , informix , h2 , sqlserver2012 , derby
特别注意:使用 sqlserver2012 数据库时,需要手动指定为 sqlserver2012 ,否则会使用 sqlserver2005 的方式进行分页。 你也可以实现 abstracthelperdialect ,然后配置该属性为实现类的全限定名称即可使用自定义的实现方法。
2. offsetaspagenum :默认值为 false ,该参数对使用 rowbounds 作为分页参数时有效。 当该参数设置为 true 时,会将 rowbounds 中的 offset 参数当成 pagenum 使用,可以用页码和页面大小两个参数进行分页。
3. rowboundswithcount :默认值为 false ,该参数对使用 rowbounds 作为分页参数时有效。当该参数设置为 true 时,使用 rowbounds 分页会进行 count 查询。   
4. pagesizezero :默认值为 false ,当该参数设置为 true 时,如果 pagesize=0 或者 rowbounds.limit = 0 就会查询出全部的结果(相当于没有执行分页查询,但是返回结果仍然是 page 类型)。
5. reasonable :分页合理化参数,默认值为 false 。当该参数设置为 true 时, pagenum<=0 时会查询第一页, pagenum>pages (超过总数时),会查询最后一页。默认 false 时,直接根据参数进行查询。
6. params :为了支持 startpage(object params) 方法,增加了该参数来配置参数映射,用于从对象中根据属性名取值, 可以配置 pagenum,pagesize,count,pagesizezero,reasonable ,不配置映射的用默认值, 默认值为 pagenum=pagenum;pagesize=pagesize;count=countsql;reasonable=reasonable;pagesizezero= pagesizezero 。
7. supportmethodsarguments :支持通过 mapper 接口参数来传递分页参数,默认值 false ,分页插件会从查询方法的参数值中,自动根据上面 params 配置的字段中取值,查找到合适的值时就会自动分页。 使用方法可以参考测试代码中的 com.github.pagehelper.test.basic 包下的 argumentsmaptest 和 argumentsobjtest 。
8. autoruntimedialect :默认值为 false 。设置为 true 时,允许在运行时根据多数据源自动识别对应方言的分页 (不支持自动选择 sqlserver2012 ,只能使用 sqlserver ),用法和注意事项参考下面的场景五。
9. closeconn :默认值为 true 。当使用运行时动态数据源或没有设置 helperdialect 属性自动获取数据库类型时,会自动获取一个数据库连接, 通过该属性来设置是否关闭获取的这个连接,默认 true 关闭,设置为 false 后,不会关闭获取的连接,这个参数的设置要根据自己选择的数据源来决定。

完整核心配置文件


doctype configuration
        public "-//mybatis.org//dtd config 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <properties resource="config.properties"/>
    <settings>
        
        <setting name="mapunderscoretocamelcase" value="true"/>
        
        <setting name="logimpl" value="stdout_logging"/>
        
        
        <setting name="lazyloadingenabled" value="true"/>
        
        
        <setting name="aggressivelazyloading" value="false"/>
        
        <setting name="cacheenabled" value="true"/>
    settings>
    <typealiases>
        
        
        
        
        <package name="com.lihaozhe.pojo"/>
        <package name="com.lihaozhe.vo"/>
    typealiases>
    <plugins>
        
        <plugin interceptor="com.github.pagehelper.pageinterceptor">
            
            <property name="helperdialect" value="mysql"/>
            
            <property name="pagesizezero" value="true"/>
            
            <property name="reasonable" value="true"/>
        plugin>
    plugins>
    
    
    <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>
        
        
        
        
        
        
        
        <package name="com.lihaozhe.mapper"/>
    mappers>
configuration>

编写接口

com.lihaozhe.mapper.personmapper

package com.lihaozhe.mapper;
import com.lihaozhe.pojo.person;
import org.apache.ibatis.annotations.param;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:47
 */
public interface personmapper {
    /**
     * 分页查询
     * @param person
     * @return
     */
    list<person> select4page(@param("person") person person);
}

编写映射的配置文件

src/main/resources/com/lihaozhe/mapper/personmapper.xml


doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lihaozhe.mapper.personmapper">
    <select id="select4page" resulttype="person">
        select *
        from `person`
        <trim prefix="where" prefixoverrides="and|or">
            <if test="person.mobile != null and person.mobile.length > 0 and person.mobile.length < 12">
                <bind name="like_mobile" value="'%'  person.mobile  '%'"/>
                and `mobile` like #{like_mobile}
            if>
            <if test="person.mobile != null and person.mobile.length > 0 and person.mobile.length < 12">
                <bind name="like_nickname" value="'%'  person.nickname  '%'"/>
                and `nickname` like #{like_nickname}
            if>
        trim>
    select>
mapper>

编写测试类

com.lihaozhe.mapper.personmappertest

package com.lihaozhe.mapper;
import cn.binarywang.tools.generator.chineseidcardnumbergenerator;
import cn.binarywang.tools.generator.chinesemobilenumbergenerator;
import cn.binarywang.tools.generator.chinesenamegenerator;
import cn.hutool.core.util.idutil;
import com.alibaba.fastjson.jsonobject;
import com.github.pagehelper.pagehelper;
import com.github.pagehelper.pageinfo;
import com.lihaozhe.pojo.person;
import com.lihaozhe.util.mybatis.mybatisutil;
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 org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import java.io.ioexception;
import java.io.reader;
import java.util.arraylist;
import java.util.list;
/**
 * @author 李昊哲
 * @version 1.0.0 2022/7/7 下午1:51
 */
public class personmappertest {
    private sqlsession sqlsession;
    // junit5 @beforeall和@beforeeach注解替换了 junit4 中的@before注解。
    // 它⽤于表⽰应在当前类中的每个@test⽅法之前执⾏注解⽅法。
    // 注意:@beforeall注解的⽅法必须为静态⽅法,否则它将引发运⾏时错误。
    // 注意:@beforeeach注解的⽅法不得为静态⽅法,否则它将引发运⾏时错误。
    @beforeeach
    public void getsqlsession() throws ioexception {
        // 核心配置文件classpath路径
        string resource = "mybatis/mybatis-config.xml";
        // 加载配置文件
        reader reader = resources.getresourceasreader(resource);
        // 构建会话工厂
        sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
        // 从sqlsessionfactory对象中获取sqlsession
        sqlsession = sqlsessionfactory.opensession();
    }
    @test
    public void select4page(){
        personmapper mapper = sqlsession.getmapper(personmapper.class);
        // 在执行代理对象中查询方法之前 开启分页
        pagehelper.startpage(10,5);
        // 准备查询条件
        person person = new person();
        // 开启分页后 执行代理对象中的查询方法
        list<person> personlist = mapper.select4page(person);
        sqlsession.close();
        pageinfo<person> pageinfo = new pageinfo<>(personlist);
        system.out.println(pageinfo);
        system.out.println(jsonobject.tojsonstring(pageinfo));
        system.out.println(jsonobject.tojsonstring(pageinfo.getlist()));
    }
}

pageinfo类属性介绍

属性名属性说明
pagenum当前页
pagesize每页的数量
size当前页的数量
startrow由于startrow和endrow不常用,这里说个具体的用法 可以在页面中"显示startrow到endrow 共size条数据" 当前页面第一个元素在数据库中的行号
endrow
pages总页数
prepage前一页
nextpage下一页
isfirstpage是否为第一页
islastpage是否为最后一页
haspreviouspage是否有前一页
hasnextpage是否有下一页
navigatepages导航页码数
navigatepagenums所有导航页号
nnavigatefirstpage导航条上的第一页
navigatelastpage导航条上的最后一页
list数据集合
total总数量

完整核心配置文件


doctype configuration
        public "-//mybatis.org//dtd config 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <properties resource="config.properties"/>
    <settings>
        
        <setting name="mapunderscoretocamelcase" value="true"/>
        
        <setting name="logimpl" value="stdout_logging"/>
        
        
        <setting name="lazyloadingenabled" value="true"/>
        
        
        <setting name="aggressivelazyloading" value="false"/>
        
        
    settings>
    <typealiases>
        
        
        
        
        <package name="com.lihaozhe.pojo"/>
        <package name="com.lihaozhe.vo"/>
    typealiases>
    <plugins>
        
        <plugin interceptor="com.github.pagehelper.pageinterceptor">
            
            
            <property name="helperdialect" value="mysql"/>
            
            <property name="pagesizezero" value="true"/>
            
            <property name="reasonable" value="true" />
        plugin>
    plugins>
    
    
    <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>
        
        
        
        
        
        <package name="com.lihaozhe.mapper"/>
    mappers>
configuration>
logo

本社区面向用户介绍csdn开发云部门内部产品使用和产品迭代功能,产品功能迭代和产品建议更透明和便捷

更多推荐