MyBatis

一、MyBatis简介

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

优点

  • 简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件易于学习,易于使用,通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
  • 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
  • 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
  • 提供映射标签,支持对象与数据库的orm字段关系映射
  • 提供对象关系映射标签,支持对象关系组建维护
  • 提供xml标签,支持编写动态sql。

jdbc:

DriverManager- --> getconnection --> prepeadStatements --> setObject --> executeQuery --resultSet --

二、第一个Mybatis程序

2.1 搭建环境

搭建数据库

CREATE DATABASE `mybatis`

CREATE TABLE `user`(
    `id` INT(20) NOT NULL AUTO_INCREMENT,
    `username` VARCHAR(40) NOT NULL,
    `password` VARCHAR(40) NOT NULL,
    PRIMARY KEY(`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT INTO `user`(`username`,`password`) VALUES
('NiKo','G2'),
('Art','Furia'),
('Yekindar','Vp')

新建项目

1.建一个maven项目
2.删掉src
3.导依赖

<dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

2.2 创建模块

  • 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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?Unicode=true &amp; characterEncoding=utf8 &amp; useSSL=true serverTimezone=Asia/Shanghai"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

</configuration>
  • 编写mybatis工具类
package com.niko.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

//sqlSessionFactory
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //Building SqlSessionFactory
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //Now that you have a SqlSessionFactory, as the name suggests, you can acquire an instance of SqlSession.
    // The SqlSession contains absolutely every method needed to execute SQL commands against the database.
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

2.3 编写代码

  • 实体类
package com.niko.pojo;

public class User {
    private Integer id;
    private String username;
    private String password;

    public User() {
    }

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

  • Dao接口 (后续全部改成Mapper)
package com.niko.dao;

import com.niko.pojo.User;

import java.util.List;

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

  • 接口实现类(由UserDaoImpl转变成Mapper配置文件)

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace 绑定一个对应的dao/Mapper接口-->
<mapper namespace="com.niko.dao.UserDao">
    <select id="getUserList" resultType="com.niko.pojo.User">
        select * from mybatis.user
    </select>
</mapper>

2.4 测试

  • junit测试
package com.niko;

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

import java.util.List;

public class TestUserDao {
    @Test
    public void TestGetUserList(){
        //获取sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();;
        try {
            //方式一:getMapper
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            List<User> userList = mapper.getUserList();

            //方式二:
            //List<User> userList = sqlSession.selectList("com.niko.dao.UseDao.getUserList");

            for (User user : userList) {
                System.out.println(user);
            }
        }finally {
            //关闭sqlSession
            sqlSession.close();
        }

    }
}

核心配置文件中注册mappers

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

注意在pom中加入资源插件,不然不会打包到target中

<build>
        <resources>
            <resource>
                <directory>src/main/java</directory><!--所在的目录-->
                <includes>
                    <!--包括目录下的.properties,.xml 文件都会扫描到-->
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory><!--所在的目录-->
                <includes>
                    <!--包括目录下的.properties,.xml 文件都会扫描到-->
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

三、CRUD

增删改查之前要提交事务:sqlSession.commit();

1 namespace

包名要和mapper接口一致

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

2 select

方法

 //select
    User getUserById(int id);

mapper配置

 <select id="getUserById" resultType="com.niko.pojo.User" parameterType="int">
        select * from mybatis.user where id =#{id}
    </select>

测试

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

3 insert

方法

//insert
    int addUser(User user);

mapper配置

 <insert id="addUser" parameterType="com.niko.pojo.User">
        insert into mybatis.user (id,username,password) values(#{id},#{username},#{password})
    </insert>

测试

@Test
    public void TestAddUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();;
        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int i = mapper.addUser(new User(null,"Simple","NaVi"));
            if (i>0){
                System.out.println("插入成功");
            }
        }finally {
            sqlSession.commit();
            sqlSession.close();
        }
    }

4 update

方法

//update
    int updateUser(User user);

mapper配置

<update id="updateUser" parameterType="com.niko.pojo.User">
        update mybatis.user set username=#{username},password=#{password} where id=#{id}
    </update>

测试

 @Test
    public void TestUpdateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();;
        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int i = mapper.updateUser(new User(4,"Shiro","Gambit"));
            if (i>0){
                System.out.println("修改成功");
            }
        }finally {
            sqlSession.commit();
            sqlSession.close();
        }
    }

5 delete

方法

//delete
    int deleteUser(int id);

mapper配置

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

测试

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

6 使用Map

 //insert 2
    int addUser2(Map<String, Object> map);
<insert id="addUser2" parameterType="map">
        insert into mybatis.user (id,username,password) values(#{userid},#{name},#{pwd})
    </insert>
  @Test
    public void TestAddUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String, Object> map = new HashMap<>();
        map.put("userid",4);
        map.put("name","S1mple");
        map.put("pwd","NaVi");
        mapper.addUser2(map);
        sqlSession.commit();
        sqlSession.close();
    }

Map 传递参数,直接在sql中取出key

单个基本参数类型可以直接在sql取到

多个参数用Map,或者注解

四、配置解析

1 核心配置文件

  • mybatis-config.xml

  • Mybatis的配置文件包含了会深深影响Mybatis行为的设置和属性信息

    configuration(配置)
    properties(属性)
    settings(设置)
    typeAliases(类型别名)
    typeHandlers(类型处理器)
    objectFactory(对象工厂)
    plugins(插件)
    environments(环境配置)
    environment(环境变量)
    transactionManager(事务管理器)
    dataSource(数据源)
    databaseIdProvider(数据库厂商标识)
    mappers(映射器)
    

2 环境配置(environments)

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

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

Mybatis默认的事务管理器是jdbc,连接池POOLED

3 属性(properties)

通过properties属性来实现引用配置文件

这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。

编写一个配置文件

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?Unicode=true & characterEncoding=utf8 & useSSL=true & serverTimezone=Asia/Shanghai
username=root
password=123456

引入外部文件(优先使用

可以加入一些属性

 <!-- 引入外部配置文件-->
    <properties resource="db.properties"/>

更改dataSource

 <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>

4 类型别名(typeAliases)

  • 类型别名可为 Java 类型设置一个缩写名字。

  • 它仅用于 XML 配置,意在降低冗余的全限定类名书写。

<typeAliases>
    <typeAlias type="com.niko.pojo.User" alias="User"/>
</typeAliases>

也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean

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

<package name="com.niko.pojo"/>

可以通过加注解@Alias来更改别名

5 设置(settings)

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

设置名 描述 有效值 默认值
cacheEnabled 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。 true | false true
lazyLoadingEnabled 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。 true | false false
logImpl 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING 未设置

6 其他

7 映射器(mappers)

MapperRegistry : 注册绑定Mapper文件

方式一:

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

方式二:

<mappers>
	<mapper class="com.niko.dao.UserMapper"/>
</mappers>

注意:

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

8 生命周期

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

SqlSessionFactory

  • 一旦创建了 SqlSessionFactory,就不再需要它了。

  • 局部方法变量

SqlSessionFactory

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

SqlSession

  • 连接到连接池的一个请求
  • 用完关闭
  • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。

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

1 问题

数据库中的字段名为 id username password

将pojo中user类的password改成pwd

再进行查询会发现输出的pwd为null

select * from mybatis.user
//类型处理器
select id,username,password as pwd from mybatis.user

解决方法:

  • 起别名
 <select id="getUserList" resultType="User">
         select id,username,password as pwd from mybatis.user
 </select>

2 resultMap

结果集映射

id username password
id username pwd 
 <resultMap id="UserMap" type="User">
        <result column="id" property="id"/>   可省略
        <result column="username" property="username"/>   可省略
        <result column="password" property="pwd"/>
    </resultMap>

    <select id="getUserById" resultMap="UserMap" parameterType="int">
        select * from mybatis.user where id =#{id}
    </select>
  • resultMap 元素是 MyBatis 中最重要最强大的元素。
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
  • ResultMap 的优秀之处——你完全可以不用显式地配置它们

六、日志

6.1 日志工厂

如果一个数据库操作出现异常,用日志方便排除错误

设置名 描述 有效值 默认值
logImpl 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING 未设置

掌握: LOG4J , STDOUT_LOGGING

STDOUT_LOGGING 标准日志输出

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

6.2 Log4j

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;

  • 我们也可以控制每一条日志的输出格式;

  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。

  • 最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

导包

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

log4j.properties:

#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file

#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/KennyS.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

配置log4j为日志的实现:

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

测试

import org.apache.log4j.Logger;
static Logger logger = Logger.getLogger(TestUserMapper.class);
@Test
public void TestLog4j(){
    logger.info("info:进入了TestLog4j");
    logger.debug("debug:进入了TestLog4j");
    logger.error("error:进入了TestLog4j");
}

七、分页

7.1 使用limit分页

select * from user limit startIndex,pageSize

使用Mybatis实现分页,核心SQL

  1. 接口
  //limit
    List<User> getUserByLimit(Map<String, Integer> map);
  1. Mapper.xml
<select id="getUserByLimit" resultMap="UserMap">
        select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
  1. 测试
 @Test
    public void TestLimit(){
        try (SqlSession sqlSession = MybatisUtils.getSqlSession()) {
            ;
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            Map<String, Integer> map = new HashMap<>();
            map.put("startIndex",0);
            map.put("pageSize",2);
            List<User> list = mapper.getUserByLimit(map);
            for (User user : list) {
                System.out.println(user);
            }
        }
    }

7.2 使用RowBounds分页

不再使用SQL实现分页

  1. 接口
  //rowBounds
    List<User> getUserByRowBounds();
  1. Mapper.xml
 <select id="getUserByRowBounds" resultMap="UserMap">
        select * from mybatis.user
    </select>
  1. 测试
@Test
    public void TestRowBounds(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        //rowBounds实现
        RowBounds rowBounds = new RowBounds(1, 2);

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

        sqlSession.close();
    }
}

7.3 分页插件

MyBatis 分页插件 PageHelper

八、使用注解开发

不推荐使用

对于像 BlogMapper 这样的映射器类来说,还有另一种方法来完成语句映射。 它们映射的语句可以不用 XML 来配置,而可以使用 Java 注解来配置。比如,上面的 XML 示例可以被替换成如下的配置:

package org.mybatis.example;
public interface BlogMapper {
  @Select("SELECT * FROM blog WHERE id = #{id}")
  Blog selectBlog(int id);
}

使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪。 因此,如果你需要做一些很复杂的操作,最好用 XML 来映射语句。

本质是反射机制,底层是动态代理

关于@Param()注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型,可以忽略
  • SQL中引用的就是@Param()中设定的属性名

九、Lombok

Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.

使用步骤

  1. 在IDEA中安装Lombok插件

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

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
        <scope>provided</scope>
    </dependency>
    
  3. 实体类上加注解

@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val
@var
experimental @var
@UtilityClass
Lombok config system
Code inspections
Refactoring actions (lombok and delombok)
@Data:无参构造,get,set,tostring,hashcode,equals...
@AllArgsConstructor
@NoArgsConstructor

十、多对一处理

多个关联一个

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

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

CREATE TABLE `student` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  `tid` INT(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fktid` (`tid`),
  CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT INTO `student` (`id`, `name`, `tid`) VALUES (1, '小明', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (2, '小红', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (3, '小张', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (4, '小李', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (5, '小王', 1);

按照查询嵌套处理

<!-- 1.查询所有的学生的信息
     2.根据学生的tid,寻找对应的老师-->
<select id="getStudent" resultMap="ST">
    select * from mybatis.student
</select>
<resultMap id="ST" type="Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <!-- 复杂的属性,我们需要单独处理 对象:association 集合:collection-->
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>

<select id="getTeacher" resultType="Teacher">
    select * from mybatis.teacher where id=#{id}
</select>

按照结果嵌套处理

<select id="getStudent" resultMap="ST2">
    select s.id sid,s.name sname,t.name tname
    from mybatis.student s,mybatis.teacher t
    where s.tid=t.id
</select>
<resultMap id="ST2" type="student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="Teacher">
        <result property="name" column="tname"
                </association>
</resultMap>

十一、一对多处理

一个关联多个

实体类:

Student:

package com.niko.pojo;
import lombok.Data;
@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}

Teacher:

@Data
public class Teacher {
    private int id;
    private String name;
    //一个老师拥有多个学生
    private List<Student> students;
}

按结果嵌套查询:

<select id="getTeacher" resultMap="TeacherStudent">
    select s.id sid,s.name sname,t.name tname,t.id tid
    from mybatis.student s,mybatis.teacher t
    where s.tid=t.id and t.id=#{tid}
</select>
<resultMap id="TeacherStudent" type="teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <!--集合中的泛型信息,我们使用ofType获取-->
    <collection property="students" ofType="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>

按照查询嵌套:

<select id="getTeacher" resultMap="TeacherStudent">
    select * from mybatis.teacher where id=#{tid}
</select>
<resultMap id="TeacherStudent" type="teacher">
    <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="student">
    select * from mybatis.student where tid=#{tid}
</select>

十二、动态SQL

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

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

环境

CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT 博客id,
`title` VARCHAR(100) NOT NULL COMMENT 博客标题,
`author` VARCHAR(30) NOT NULL COMMENT 博客作者,
`create_time` DATETIME NOT NULL COMMENT 创建时间,
`views` INT(30) NOT NULL COMMENT 浏览量
)ENGINE=INNODB DEFAULT CHARSET=utf8

实体类:

package com.niko.pojo;

import lombok.Data;

import java.util.Date;

@Data
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;
    private int views;
}

IF

 <select id="queryBlogIF" parameterType="map" resultType="blog">
        select * from mybatis.blog where 1=1
        <if test="title!=null">
            and title=#{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
    </select>

Choose

Sometimes we don’t want all of the conditionals to apply, instead we want to choose only one case among many options.

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

trim(where,set)

select * from mybatis.blog
        <where>
        <if test="title!=null">
            and title=#{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
        </where>

the set element will dynamically prepend the SET keyword, and also eliminate any extraneous commas that might trail the value assignments after the conditions are applied.

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

自定义:

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

sql片段

可以实现一些代码的复用(封装)

 <sql id="if-title-author">
        <if test="title!=null">
            title=#{title},
        </if>
        <if test="author!=null">
            author=#{author}
        </if>
    </sql>

 <update id="updateBlog" parameterType="map">
        update mybatis.blog
        <set>
           <include refid="if-title-author"/>
        </set>
        where id=#{id}
    </update>

foreach

<select id="queryForeach" parameterType="map" resultType="student">
    select * from  mybatis.student
    <where>
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id=#{id}
        </foreach>
    </where>
</select>
HashMap<Object, Object> map = new HashMap<>();
ArrayList<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
map.put("ids",ids);

mapper.queryForeach(map);

十三、缓存

提高效率

13.1 Mybatis缓存

  • MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制。
  • Mybatis系统中默认定义了两级缓存:一级缓存二级缓存
    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
    • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存
    • 为了提高扩展性,Mybatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存

13.2 一级缓存

  • 一级缓存也叫本地缓存:sqlsession (默认开启)
    • 与数据库同一次会话期间查询到的数据会放在本地缓存中
    • 以后若需要获取相同的数据,直接从缓存中取,不用再查询数据库

1、开启日志

2、测试在一个session中查询两次相同记录

User user = mapper.queryUserById(1);
System.out.println(user);

System.out.println("=======================");

User user1 = mapper.queryUserById(1);
System.out.println(user1);

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

3、查看日志输出

Opening JDBC Connection
Created connection 1722570594.
==>  Preparing: select * from mybatis.user where id=?
==> Parameters: 1(Integer)
<==    Columns: id, username, password
<==        Row: 1, NiKo, G2
<==      Total: 1
User(id=1, username=NiKo, password=G2)
=======================
User(id=1, username=NiKo, password=G2)
true
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@66ac5762]
Returned connection 1722570594 to pool.

缓存失效的情况:

增删改查操作,会刷新缓存

手动清理缓存:sqlSession.clearCache();

13.3 二级缓存

要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:

<cache/>

基本上就是这样。这个简单语句的效果如下:

  • 映射语句文件中的所有 select 语句的结果将会被缓存。

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

  • 缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。

  • 缓存不会定时进行刷新(也就是说,没有刷新间隔)。

  • 缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。

  • 缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改

    ​ namespace级别

  • 工作机制:

    • 一个会话查询一条数据,这个数据就会被放在当前对话的一级缓存中;
    • 如果当前会话关闭,一级缓存就没了,但是我们想在一级缓存关闭后数据保存到二级缓存中
    • 新的会话查询信息就可以直接从二级缓存中获取
    • 不同的mapper查出的数据会放在自己对应的缓存中

1、显式开启全局缓存:

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

2、在要使用二级缓存的mapper中开启

<cache
  eviction="FIFO"
  flushInterval="60000"
  size="512"
  readOnly="true"/>


<select useCache="true">

3、测试

Cache Hit Ratio [com.niko.dao.UserMapper]: 0.0
Opening JDBC Connection
Created connection 1998949977.
==>  Preparing: select * from mybatis.user where id=?
==> Parameters: 1(Integer)
<==    Columns: id, username, password
<==        Row: 1, NiKo, G2
<==      Total: 1
User(id=1, username=NiKo, password=G2)
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@77258e59]
Returned connection 1998949977 to pool.
=======================
Cache Hit Ratio [com.niko.dao.UserMapper]: 0.5
User(id=1, username=NiKo, password=G2)
true

可用的清除策略有:

  • LRU – 最近最少使用:移除最长时间不被使用的对象。
  • FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
  • SOFT – 软引用:基于垃圾回收器状态和软引用规则移除对象。
  • WEAK – 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。

默认的清除策略是 LRU。

13.4 自定义缓存 Ehcache

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。

<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.9.4</version>
</dependency>

ehcache.xml

<?xml version="1.0" encoding="UTF-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">

    <diskStore path="./tmpdir/Tmp_EhCache"/>

    <defaultCache
            eternal="false"
            maxElementsInMemory="10000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"/>

    <cache
            name="cloud_user"
            eternal="false"
            maxElementsInMemory="5000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="1800"
            memoryStoreEvictionPolicy="LRU"/>
</ehcache>
posted @ 2021-06-30 11:52  Un1verse  阅读(77)  评论(0)    收藏  举报