环境

  • JDK1.8
  • MySQL
  • Maven
  • IDEA

回顾

  • JDBC
  • MySQL
  • Java基础
  • Maven
  • Junit
  • SSM框架

Mybatis简介

  • 什么是 MyBatis?

    • MyBatis 是一款优秀的「持久层框架」。
    • 它支持自定义 SQL、存储过程以及高级映射。
    • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
    • MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
    • MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。
    • 2013年11月迁移到Github。
  • 怎么获得Mybatis?

  • 持久化

    • 数据持久化,持久状态和瞬时状态的转化
    • 内存:断电即失
    • 数据库(JDBC),IO文件持久化
  • 持久层

    • Dao层、Service层、Controller层
    • 完成持久化工作的代码块
    • 层次界限十分明显
  • 为什么使用Mybatis?

    • 简化JDBC,自动化

第一个Mybatis项目

  • 搭建环境

    • 创建数据库和表
    • 创建Maven项目
    • 删除项目中的src目录(使之成为父级项目)
    • 新建module(Maven类型)
    • 导入依赖:mybatis、junit...
  • 在resource目录创建Mybatis配置文件:mybatis-config.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/jdbc_test?useSSL=false&amp;characterEncoding=utf8&amp;serverTimezone=Asia/Shanghai"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <!-- 每一个Mapper.xml都要在Mybatis核心配置文件中注册! -->
            <mapper resource="cn/cnyasin/dao/UserMapper.xml"/>
        </mappers>
    </configuration>
  • 创建自己的一个Mybatis工具类:package cn.cnyasin.utils;

    public class MybatisUtils {
        private static SqlSessionFactory sqlSessionFactory;
        private static String resource = "mybatis-config.xml";
        private static InputStream inputStream = null;
        /**
         * 从 XML 中构建 SqlSessionFactory
         */
        static {
            try {
                inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != inputStream) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        /**
         * 从 SqlSessionFactory 中获取 SqlSession
         * @return SqlSession
         */
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
    }
  • 创建pojo

    public class User {
        private int id;
        private String username;
        private String email;
        private String password;
        private long balance;
        private long created_at;
        // ...
    }
  • 在pom.xml中开启java目录资源过滤,Mybatis读取Mapper.xml需要该配置

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

    注意:src/main/resourcessrc/main/java两个都要打开,resources如果不配置默认只开启src/main/resources目录,反之,如果配置了就会覆盖默认值。

    注意:如果需要读取xml配置就开启**/*.xml,如果你需要读取properties配置就开启**/*.properties

  • 创建dao:package cn.cnyasin.dao;

    public interface UserMapper {
        // 查询一个用户
        User getOne(@Param("id") int id);
        // 查询所有用户
        List<User> getAll();
        // 添加一个用户
        int addOne(User user);
        // 修改一个用户
        int updateOne(User user);
        // 删除一个用户
        int deleteOne(int id);
    }
  • 创建Mapper:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <!-- 一个namespace对应一个Mapper类(原来的dao) -->
    <mapper namespace="cn.cnyasin.dao.UserMapper">
        <!--
        id:一个id对应一个方法
        resultType:返回一个结果
        resultMap:返回多个结果
        -->
        <!-- 查询一个用户 -->
        <select id="getOne" resultType="cn.cnyasin.pojo.User">
            select * from user where id = #{id}
        </select>
        <!-- 查询所有用户 -->
        <select id="getAll" resultMap="userListMap">
            select * from user
        </select>
        <!-- 添加一个用户 -->
        <insert id="addOne" parameterType="cn.cnyasin.pojo.User">
            insert into user (`username`,`email`,`password`,`created_at`) values (#{username}, #{email}, #{password}, #{created_at})
        </insert>
        <!-- 修改一个用户 -->
        <update id="updateOne" parameterType="cn.cnyasin.pojo.User">
            update user set balance = #{balance} where id = #{id};
        </update>
        <!-- 删除一个用户 -->
        <delete id="deleteOne">
            delete from user where id = #{id}
        </delete>
        <resultMap id="userListMap" type="cn.cnyasin.pojo.User"/>
    </mapper>
  • 测试

    @Test
    public void getOneTest()
    {
        // 获取SQLSession
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        // getMapper
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.getOne(1);
        System.out.println(user);
        System.out.println("----------------------------");
        List<User> users = userMapper.getAll();
        for (User user1 : users) {
            System.out.println(user1);
        }
        // 关闭SQLSession
        sqlSession.close();
    }
    @Test
    public void updateOneTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getOne(6);
        if (null == user) {
            System.out.println("用户不存在。。。");
            return;
        }
        user.setBalance(user.getBalance() + 100000);
        int updateOne = mapper.updateOne(user);
        if (updateOne > 0) {
            System.out.println("用户余额更新成功。。。");
        }
        sqlSession.commit();
        sqlSession.close();
    }
    // 增加、删除的测试方法省略。。。

遇到的问题

  • MySQL连接异常:The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. ...

    • 原因分析:如果mysql的jar包使用了8.*版本,该版本要求必须显式的指定serverTimezone
    • 解决方案:

      <property name="url" value="jdbc:mysql://localhost:3306/jdbc_test?useSSL=false&amp;characterEncoding=utf8&amp;serverTimezone=Asia/Shanghai"/>
  • MySQL链接异常:org.xml.sax.SAXParseException; lineNumber: 11; columnNumber: 113; 对实体 "characterEncoding" 的引用必须以 ';' 分隔符结尾。...

    • 原因分析:xml配置文件特殊符号必须转实体(&->&amp;),properties配置文件则不需要(&)。
    • 解决方案:xml配置中将url中的&改成&amp;,properties配置中则相反。
  • 启动报错,找不到XxxMapper.xml:The error may exist in cn/cnyasin/dao/UserMapper.xml...

    • 原因分析:Maven资源过滤问题。Maven默认资源过滤文件目录为resources目录,java目录下的文件是不会被导出的,需要手动开启该目录的资源过滤。
    • 解决方案:在pom.xml中添加如下代码:

      <build>
          <resources>
              <resource>
                  <directory>src/main/resources</directory>
                  <includes>
                      <include>**/*.properties</include>
                      <include>**/*.xml</include>
                  </includes>
              </resource>
              <resource>
                  <directory>src/main/java</directory>
                  <includes>
                      <include>**/*.properties</include>
                      <include>**/*.xml</include>
                  </includes>
              </resource>
          </resources>
      </build>
      > 注意:`src/main/resources`、`src/main/java`两个都要打开,resources如果不配置默认只开启`src/main/resources`目录,反之,如果配置了就会覆盖默认值。
      
      > 注意:如果需要读取xml配置就开启`**/*.xml`,如果你需要读取properties配置就开启`**/*.properties`。
      

补充说明

  • 如果参数比较多又不方便传一个pojo,可以考虑传一个Map,俗称“万能map”。
  • 模糊查询怎么写?

    • 方式一参数这么传:value=%张三%
    • 方式二SQL这么写:select * from user where name like "%"#{value}"%"

配置解析

  • 核心配置文件

    • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:

      • configuration(配置)

        • properties(属性)
        • settings(设置)
        • typeAliases(类型别名)
        • typeHandlers(类型处理器)
        • objectFactory(对象工厂)
        • plugins(插件)
        • environments(环境配置)

          • environment(环境变量)

            • transactionManager(事务管理器)
            • dataSource(数据源)
        • databaseIdProvider(数据库厂商标识)
        • mappers(映射器)
    • 具体参考官方文档:https://mybatis.org/mybatis-3/zh/configuration.html#
  • 环境配置(environments)

    • Mybatis可以实现连接多个数据库
    • 不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
    • 如果你想连接两个数据库,就需要创建两个 SqlSessionFactory 实例,每个数据库对应一个。
    • 事务管理器(transactionManager)

      • 在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]"),默认JDBC。
      • JDBC:我理解是对事务友好。
      • MANAGED:我理解是适用于容器使用完连接后需要手动关闭的情况。
      • 如果你正在使用 Spring + MyBatis,则没有必要配置事务管理器,因为 Spring 模块会使用自带的管理器来覆盖前面的配置。
    • 数据源(dataSource)

      • 有三种内建的数据源类型(也就是 type="[UNPOOLED|POOLED|JNDI]")
      • UNPOOLED:没有池子,适用于小型网站,慢点但节省资源。
      • POOLED:有池子,适用于大型高并发网站,响应速度更快。
      • JNDI:用的不多就不说了。
  • 属性(properties)

    • 优先级:.properties > property标签
  • 类型别名(typeAliases)

    • 作用:简化xml
    • 用法一:

      <typeAliases>
          <typeAlias type="cn.cnyasin.pojo.User" alias="user"/>
      </typeAliases>
    • 用法二:每一个在包cn.cnyasin.pojo中的JavaBean,在没有注解的情况下,会使用Bean的首字母小写的非限定类名来作为它的别名。若有注解,则别名为其注解值。

      <typeAliases>
          <package name="cn.cnyasin.pojo"/>
      </typeAliases>
      @Alias("user001")
      public class User {}
  • 设置(settings)
  • 映射器(mappers)
  • 其他配置。。。

生命周期

  • SqlSessionFactoryBuilder:创建SqlSessionFactory用的,一次性。
  • SqlSessionFactory:在应用的运行期间一直存在。
  • SqlSession:最佳的作用域是请求或方法中,方法调用结束后销毁。

结果映射(resultMap )

  • 主要用于处理复杂的SQL
  • 其中重要的一个作用:解决类属性和字段名不一致

    <!-- user读取的mybatis核心配置文件中定义的类型别名 -->
    <resultMap id="userListMap" type="user">
        <!-- 结果集映射:解决类属性和字段名不一致 -->
        <result column="created_at" property="createdAt"/>
    </resultMap>

日志

  • 如果数据库操作异常我们需要拍错,就需要用到日志
  • 日志工厂

    • 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。
    • 在mybatis设置中进行设置:设置(settings) -> logImpl,默认未设置(不输出详细日志),支持的选项:

      • SLF4J
      • LOG4J(掌握)
      • LOG4J2
      • JDK_LOGGING
      • COMMONS_LOGGING
      • STDOUT_LOGGING(掌握)
      • NO_LOGGING
  • STDOUT_LOGGING:标准日志输出,mybatis内置,不用手动导包,设置了该选项后自动输出日志。

    <settings>
        <!-- 开启日志 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
  • LOG4J:强大的日志工具,需要手动导包。

    • 什么是log4j?

      • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;
      • 我们也可以控制每一条日志的输出格式;
      • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
      • 最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
    • 如何基本使用?

      • 导入包

        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
      • 在mybatis核心配置文件将settings中的logImpl选项设置为LOG4J

        <settings>
            <!-- 开启日志 -->
            <setting name="logImpl" value="LOG4J"/>
        </settings>
      • 在classpath(resources)目录创建log4j的配置文件:log4j.properties(固定名字),一个简单的配置文件如下:

        log4j.rootLogger=DEBUG,console,file
        #控制台输出的相关设置
        log4j.appender.console=org.apache.log4j.ConsoleAppender
        log4j.appender.console.Target=System.out
        log4j.appender.console.Threshold=DEBUG
        log4j.appender.console.layout=org.apache.log4j.PatternLayout
        log4j.appender.console.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
        #文件输出的相关设置
        log4j.appender.file=org.apache.log4j.RollingFileAppender
        log4j.appender.file.File=./log/logs.txt
        log4j.appender.file.MaxFileSize=10mb
        log4j.appender.file.Threshold=DEBUG
        log4j.appender.file.layout=org.apache.log4j.PatternLayout
        log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
        #日志输出级别
        log4j.logger.org.mybatis=DEBUG
        log4j.logger.java.sql=DEBUG
        log4j.logger.java.sql.Statement=DEBUG
        log4j.logger.java.sql.ResultSet=DEBUG
        log4j.logger.java.sql.PreparedStatement=DEBUG
        • log4j.rootLogger=DEBUG,console,file:意思是日志输出级别为DEBUG,输出到控制台、文件
        • 其它详细配置自己研究吧
    • 如何手动使用?

      • 前提:配置好了log4j基本使用
      • 在要手动输出日志的类中定义一个日志对象
      • 在适当的位置调用该日志对象的相关方法
      • 核心代码

        public class UserMapperTest {
            private static Logger logger = Logger.getLogger(UserMapperTest.class);
            @Test
            public void log4jTest() {
                // 错误级别:debug < info < warn < error,级别越低输出的日志越详细
                logger.debug("hahaha...呵呵。。。");
                logger.info("hahaha...呵呵。。。");
                logger.warn("hahaha...呵呵。。。");
                logger.error("hahaha...呵呵。。。");
            }
        }

分页

  • 借助Map传start、pageSize给Mapper.xml,然后SQL中使用limit语句实现(推荐)。
  • RowBounds
  • PageHelper插件

使用注解开发

  • 说明:适用于简单逻辑,复杂的逻辑不适合注解,比如字段属性映射关系就实现不了。
  • 原理:反射、动态代理
  • 注意:

    • 如果接口上加了注解,那么同目录下务必不要有对应的Mapper.xml文件,或者Mapper.xml中不要定义同id的方法,会冲突。
    • 如果方法上有多个参数,务必在每个参数前加上@Param()注解。
  • 具体实现步骤

    • 环境准备(略)
    • 注解在接口上实现

      public interface UserMapper {
          @Select("select * from user where id = #{id}")
          User getOne(int id);
      }
    • mybatis核心配置文件中的mappers映射器中加载类

      <mappers>
          <mapper class="cn.cnyasin.dao.UserMapper"/>
      </mappers>
    • 测试

lombok的使用

  • 简介

    • Java使用工具。简化Javabean(POJO)的,免去Getter/Setter/Constructor/toString.....。
  • 用法(idea)

    • 在idea的设置中的插件设置里搜索lombok进行安装,然后按提示会让你重启idea,重启后默认开启该插件支持,要关闭可以再次打开idea的插件设置项,找到installed,禁用或者卸载。
    • 在要使用该用具的项目中加入lombok包依赖

      <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
      <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>1.18.12</version>
      </dependency>
    • 在POJO中使用
  • 支持的注解

    @Getter and @Setter
    @FieldNameConstants
    @ToString
    @EqualsAndHashCode
    @AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
    @Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
    @Data
    @Builder
    @SuperBuilder
    @Singular
    @Delegate
    @Value
    @Accessors
    @Wither
    @With
    @SneakyThrows
    @val
    @var
    experimental @var
    @UtilityClass
    @ExtensionMethod (Experimental, activate manually in plugin settings)

关联嵌套查询

  • 属性列表

    • constructor - 用于在实例化类时,注入结果到构造方法中

      • idArg - ID 参数;标记出作为 ID 的结果可以帮助提高整体性能
      • arg - 将被注入到构造方法的一个普通结果
    • id – 一个 ID 结果;标记出作为 ID 的结果可以帮助提高整体性能
    • result – 注入到字段或 JavaBean 属性的普通结果
    • association – 一个复杂类型的关联;许多结果将包装成这种类型

      • 嵌套结果映射 – 关联可以是 resultMap 元素,或是对其它结果映射的引用
    • collection – 一个复杂类型的集合

      • 嵌套结果映射 – 集合可以是 resultMap 元素,或是对其它结果映射的引用
    • discriminator – 使用结果值来决定使用哪个 resultMap

      • case – 基于某些值的结果映射

        • 嵌套结果映射 – case 也是一个结果映射,因此具有相同的结构和元素;或者引用其它的结果映射
  • 其他常用属性

    • property:映射到列结果的字段或属性。
    • column:数据库中的列名,或者是列的别名。
    • select:用于加载复杂类型属性的映射语句的ID,它会从column属性中指定的列检索数据,作为参数传递给此select语句。对外部select的命名引用。
    • resultMap:对外部resultMap的命名引用。
    • resultType:期望从这条语句中返回结果的类全限定名或别名,比如:User。
    • type:ResultMap的专用属性,该结果返回的类型,接受类的完全限定名或者一个类型别名,比如:User。
    • ofType:collection的专用属性,该结果集返回的类型,接受类的完全限定名或者一个类型别名,比如:User。
    • javaType:association的专用属性,一个Java类的全限定名或一个类型别名,比如:ArrayList。MyBatis通常可以自动推断类型。
  • 具体实现核心代码

    • 按查询嵌套

      <!-- 多对一(association) -->
      <select id="getOne" resultMap="studentMap">
      select * from student where id = #{id}
      </select>
      <resultMap id="studentMap" type="Student">
      <result property="createdAt" column="created_at"/>
      <result property="tid" column="tid"/>
      <association property="teacher" column="tid" javaType="Teacher" select="_getTeacher"/>
      </resultMap>
      <select id="_getTeacher" resultType="Teacher">
      select * from teacher where id = #{id}
      </select>
      <!-- ———————————————————————————————————————————————— -->
      <!-- 一对多(collection) -->
      <select id="getOne" resultMap="teacher">
      select * from teacher where id = #{id}
      </select>
      <resultMap id="teacher" type="Teacher">
      <id property="id" column="id"/>
      <result property="createdAt" column="created_at"/>
      <collection property="students" column="id" ofType="Student" select="student">
      <id property="id" column="id"/>
      </collection>
      </resultMap>
      <select id="student" resultType="Student">
      select id,name,created_at createdAt from student where tid = #{id}
      </select>
    • 按结果嵌套

      <!-- 多对一(association) -->
      <select id="getOne2" resultMap="studentResult">
      select s.*, t.`name` tName, t.created_at tCreatedAt
      from student s, teacher t
      where s.tid = t.id
      and s.id = #{id};
      </select>
      <resultMap id="studentResult" type="Student">
      <id property="id" column="id"/>
      <result property="name" column="name"/>
      <result property="tid" column="tid"/>
      <result property="createdAt" column="created_at"/>
      <association property="teacher" column="tid" javaType="Teacher" resultMap="teacherResult"/>
      </resultMap>
      <resultMap id="teacherResult" type="Teacher">
      <id property="id" column="tid"/>
      <result property="name" column="tName"/>
      <result property="createdAt" column="tCreatedAt"/>
      </resultMap>
      <!-- ————————————————————————————————————————————————— -->
      <!-- 一对多(collection) -->
      <!-- 方式一 -->
      <select id="getOne2" resultMap="teacher2">
      select
      t.id t_id, t.name t_name, t.created_at t_created_at,
      s.id s_id, s.name s_name, s.created_at s_created_at
      from teacher t, student s
      where s.tid = t.id
      and t.id = #{id}
      </select>
      <resultMap id="teacher2" type="Teacher">
      <id property="id" column="t_id"/>
      <result property="name" column="t_name"/>
      <result property="createdAt" column="t_created_at"/>
      <collection property="students" column="id" ofType="Student" resultMap="student2"/>
      </resultMap>
      <resultMap id="student2" type="Student">
      <id property="id" column="s_id"/>
      <result property="name" column="s_name"/>
      <result property="createdAt" column="s_created_at"/>
      </resultMap>
      <!-- 方式二 -->
      <select id="getOne3" resultMap="teacher3"></select>
      <resultMap id="teacher3" type="Teacher">
      <id property="id" column="t_id"/>
      <result property="name" column="t_name"/>
      <result property="createdAt" column="t_created_at"/>
      <collection property="students" column="id" ofType="Student">
      <id property="id" column="s_id"/>
      <result property="name" column="s_name"/>
      <result property="createdAt" column="s_created_at"/>
      </collection>
      </resultMap>

动态SQL

  • 概念

    • 你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
  • 常用标签

    • if
    • choose (when, otherwise)
    • trim (where, set)
    • foreach
  • 环境准备(略)
  • 具体实现核心代码

    <!-- getAll -->
    <resultMap id="userListResult" type="User">
        <id property="id" column="id"/>
        <result property="createdAt" column="created_at"/>
    </resultMap>
    <select id="getAll" resultMap="userListResult">
        select * from user
        <where>
            <if test="username != null">
                `username` = #{username}
            </if>
            <if test="email != null">
                and `email` = #{email}
            </if>
            <if test="password != null">
                and `password` = #{password}
            </if>
            <if test="ids != null">
                and id in
                <foreach collection="ids" item="id" open="(" separator="," close=")">
                    #{id}
                </foreach>
            </if>
        </where>
        <choose>
            <when test="sort != null">
                order by `id` desc
            </when>
            <otherwise>
                order by `id` asc
            </otherwise>
        </choose>
    </select>
    
    <!-- updateOne -->
    <update id="updateOne" parameterType="User">
        update user
        <set>
            <if test="username != null">`username` = #{username}</if>
            <if test="email != null">`email` = #{email}</if>
            <if test="password != null">`password` = #{password}</if>
            <if test="balance != null">`balance` = #{balance}</if>
        </set>
        where id = #{id}
    </update>
  • SQL片段

    • 使用sql标签抽取公共部分

      <sql id="sql-where">
          <if test="username != null">
      `username` = #{username}
          </if>
          <if test="email != null">
      and `email` = #{email}
          </if>
          <if test="password != null">
      and `password` = #{password}
          </if>
          <if test="ids != null">
      and id in
      <foreach collection="ids" item="id" open="(" separator="," close=")">
      #{id}
      </foreach>
          </if>
      </sql>
    • 在要使用片段的地方用include标签引用

      <where>
          <include refid="sql-where"></include>
      </where>

缓存

  • 一级缓存

    • 默认开启
    • 默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存。
    • 相同的SQL,同一个会话只会执行一次(如果期间未执行非select语句)。
  • 二级缓存

    • 要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:<cache/>
    • 效果如下

      • 映射语句文件中的所有 select 语句的结果将会被缓存。
      • 映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
      • 缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
      • 缓存不会定时进行刷新(也就是说,没有刷新间隔)。
      • 缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
      • 缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
    • 二级缓存也叫全局缓存,一个namespace一个二级缓存。
    • 二级缓存可跨会话有效。

标签: Java, Mybatis

添加新评论


手机号仅后台超管可见,普通注册用户以及网站前台全站不可见,请勿担心泄露风险!