狂神说学习笔记:MyBatis

1|0Mybatis

环境:

  • JDK1.8
  • MySQL5.7
  • maven3.6.1
  • IDEA

回顾:

  • JDBC
  • MySQL
  • Java基础
  • Maven
  • Junit

1|11、简介

1|01.1、什么是Mybatis

MyBatis logo

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

如何获取MyBatis?

1|01.2、持久化

数据持久化

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

为什么需要持久化?

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

  • 内存太贵

1|01.3、持久层

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

1|01.4、为什么需要MyBatis?

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

  • 方便

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

  • 不用MyBatis也可以,但是更容易上手(技术没有高低之分

  • 优点:

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

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

1|22、第一个MyBatis

思路:搭建环境--->导入MyBatis-->编写代码-->测试

1|02.1、搭建环境

搭建数据库

CREATE DATABASE `mybatis`; USE `mybatis`; CREATE TABLE `user`( `id` INT(20) NOT NULL, `name` VARCHAR(30) DEFAULT NULL, `pwd` VARCHAR(30) DEFAULT NULL, PRIMARY KEY(`id`) )ENGINE=INNODB DEFAULT CHARSET=utf8; INSERT INTO `user`(`id`,`name`,`pwd`) VALUES (1,'dt','123456'),(2,'张三','123456'),(3,'李四','123456');

新建项目

  1. 新建一个普通的maven项目

  2. 删除src目录

  3. 导入maven依赖

    <!--导入依赖--> <dependencies> <!--MySql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!--MyBatis--> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.9</version> </dependency> <!--Junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>

1|02.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核心配置文件--> <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/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> </configuration>
  • 编写MyBatis工具类

    MyBatisUtils.java

    package com.dt.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; /** * Created with IntelliJ IDEA. * * @author Dt * @Project MyBatis-Study * @Title: MyBatisUtils * @Package com.dt.utils * @Description: sqlSessionFactory --> sqlSession * @date 2022/4/4 11:25 */ public class MyBatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { //获取sqlSessionFactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。 // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。 public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(); } }

1|02.3、编写代码

  • 实体类

    User.java

    package com.dt.pojo; public class User { private int id; private String name; private String pwd; public User() { } public User(int id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } public long getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } }
  • Dao接口

    UserDao.java

    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.dt.dao.UserDao"> <!--select查询语句--> <select id="getUserList" resultType="com.dt.pojo.User"> SELECT * FROM mybatis.user </select> </mapper>

1|02.4、测试

注意点:

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

image-20220404123336124

MapperRegistry是什么?Mapper没有注册

解决办法:在MyBatis核心配置文件里注册Mapper

image-20220404125246444

1|02.4.1、资源导出解决

在每个项目的porn.xml中加入以下代码,以防资源导出失败

<!--在build中配置resources,来防止我们资源导出失败的问题--> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
  • Junit测试

    @Test public void getUserListTest() { //第一步:获得SqlSession对象 SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { //方式一:getMapper UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.getUserList(); //方式二: // List<User> userList = sqlSession.selectList("com.dt.dao.UserDao.getUserList"); for (User user : userList) { System.out.println(user); } } catch (Exception e) { } finally { //关闭sqlSession sqlSession.close(); } }

可能会遇到的问题:

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

1|33、CRUD

1|03.1、namespace

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

1|03.2、select

选择,查询语句

  • id:就是对应的namespace中的方法名
  • resultType:SQL语句的返回值!
  • parameterType:参数类型!
  1. 编写接口

    /** * 根据Id查询用户 * @param id * @return User */ User getUserById(int id);
  2. 编写对应的mapper中的SQL语句

    <select id="getUserById" parameterType="int" resultType="com.dt.pojo.User"> select * FROM mybatis.user WHERE id = #{id} </select>
  3. 测试

    @Test public void getUserByIdTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } }

1|03.3、insert

  1. 编写接口

    /** * 添加一个用户 * @param user * @return int */ int addUser(User user);
  2. 编写对应的mapper中的SQL语句

    <!--对象中是属性,可以直接取出来--> <insert id="addUser" parameterType="com.dt.pojo.User"> insert into mybatis.user (id, name, pwd) values (#{id}, #{name}, #{pwd}); </insert>
  3. 测试

    @Test public void addUserTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); int updateRows = mapper.addUser(new User(7, "钱七", "123456")); if (updateRows > 0) { System.out.println("添加成功"); } sqlSession.commit(); } catch (Exception e) { sqlSession.rollback(); } finally { sqlSession.close(); } }

1|03.4、update

  1. 编写接口

    /** * 修改用户 * @param user * @return int */ int updateUser(User user);
  2. 编写对应的mapper中的SQL语句

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

    @Test public void updateUserTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); int updateRows = mapper.updateUser(new User(1, "KyDestroy", "654321")); if (updateRows > 0) { System.out.println("修改成功"); } sqlSession.commit(); } catch (Exception e) { sqlSession.rollback(); } finally { sqlSession.close(); } }

1|03.5、delete

  1. 编写接口

    /** * 删除用户 * @param id * @return int */ int deleteUser(int id);
  2. 编写对应的mapper中的SQL语句

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

    @Test public void deleteUserTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); int updateRows = mapper.deleteUser(5); if (updateRows > 0) { System.out.println("删除成功"); } sqlSession.commit(); } catch (Exception e) { sqlSession.rollback(); } finally { sqlSession.close(); } }

注意点:

  • 增删改需要提交事务!

1|03.6、分析错误

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

1|03.7、万能Map

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

  • 接口

    /** * 万能Map * @param map * @return int */ int addUser2(Map<String, Object> map);
  • 对应的mapper中的SQL语句

    <!--对象中是属性,可以直接取出来 传递map的key --> <insert id="addUser2" parameterType="map"> insert into mybatis.user (id, name, pwd) values (#{userid}, #{userName}, #{passWord}); </insert>
  • 测试

    @Test public void addUser2Test() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); Map<String, Object> map = new HashMap<>(); map.put("userid", 5); map.put("userName", "赵六"); map.put("passWord", "123456"); int updateRows = mapper.addUser2(map); if (updateRows > 0) { System.out.println("插入成功"); } sqlSession.commit(); } catch (Exception e) { sqlSession.rollback(); } finally { sqlSession.close(); } }

Map传参与实体类传参的区别:

  • Map传递数据,直接在sql中取出key即可!【parameterType="map"】

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

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

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

1|03.8、模糊查询

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

    List<User> userList = mapper.getUserLike("%李%");
  2. 在SQL拼接中使用通配符!

    SELECT * FROM mybatis.user WHERE name LIKE "%"#{value}"%";
  3. 使用concat函数连接字符串

    SELECT * FROM mybatis.user WHERE name LIKE CONCAT("%", #{value}, "%");

接口:

/** * 模糊查询用户 * @return List<User> * @param value */ List<User> getUserLike(String value);

对应的mapper中的SQL语句:

<select id="getUserLike" resultType="com.dt.pojo.User"> SELECT * FROM mybatis.user WHERE name LIKE CONCAT("%", #{value}, "%"); </select>

测试:

@Test public void getUserLikeTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.getUserLike("李"); for (User user : userList) { System.out.println(user); } } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } }

1|44、配置解析

1|04.1、核心配置文件

  • mybatis-config.xml

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

    image-20220406102927360

1|04.2、环境配置(environments)

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

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

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

MyBatis默认的事务管理器:JDBC,默认连接池:POOLED

1|04.3、属性(properties)

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

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

编写一个配置文件:

driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username=root password=123456

在核心配置文件中引入:

<properties resource="org/mybatis/example/config.properties"> <property name="username" value="root"/> <property name="password" value="123456"/> </properties>
  • 可以直接引入外部文件
  • 可以在其中增加一些属性配置
  • 如果两个文件有同一个字段,优先使用外部配置文件的!

1|04.4、类型别名(typeAliases)

  • 类型别名可为 Java 类型设置一个缩写名字
  • 意在降低冗余的全限定类名书写
<!--可以给实体类取别名--> <typeAliases> <typeAlias type="com.dt.pojo.User" alias="User"/> </typeAliases>

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

每一个在包中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名(大写也可以,但不推荐)

<!--可以给实体类取别名--> <typeAliases> <package name="com.dt.pojo"/> </typeAliases>

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

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

第一种可以DIY别名,第二种则不行,需要通过注解@Alias来DIY别名

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

1|04.5、设置(settings)

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

image-20220406161548102

image-20220406161449961

1|04.6、其他配置

  • typeHandlers(类型处理器)
  • objectFactory(对象工厂)
  • plugins(插件)
    • mybatis-generator-core
    • mybatis-plus
    • 通用mapper

1|04.7、映射器(mappers)

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

方式一:【推荐使用】

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

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

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

注意点:

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

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

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

注意点:

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

1|04.8、生命周期和作用域(Scope)

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

SqlSessionFactoryBuilder

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

SqlSessionFactory

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

SqlSession

  • 连接到连接池的一个请求
  • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
  • 用完后需要赶紧关闭,否则资源被占用!

1|55、解决属性名和字段名不一致的问题

1|05.1、问题

数据库中的字段

image-20220407113706999

新建一个项目,拷贝之前的,测试实体类字段不一致的情况

public class User { private int id; private String name; private String password;

出现问题:

image-20220407123714547

//select * FROM mybatis.user WHERE id = #{id}; //类型处理器 //select id,name,pwd FROM mybatis.user WHERE id = #{id};

解决方法:

  • 起别名

    <select id="getUserById" parameterType="int" resultType="com.dt.pojo.User"> select id,name,pwd as password FROM mybatis.user WHERE id = #{id}; </select>

1|05.2、resultMap

结果集映射

数据库 id name pwd
实体类 id name password
<!--结果集映射--> <resultMap id="UserMap" type="User"> <!--column数据库中的字段,property实体类中的属性--> <result column="id" property="id"/> <result column="name" property="name"/> <result column="pwd" property="password"/> </resultMap> <select id="getUserById" parameterType="int" resultMap="UserMap"> select * FROM mybatis.user WHERE id = #{id}; </select>
  • resultMap 元素是 MyBatis 中最重要最强大的元素
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了
  • ResultMap 的优秀之处——你完全可以不用显式地配置它们

1|66、日志

1|06.1、日志工厂

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

image-20220406161449961

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

在MyBatis中具体使用哪个日志实现,在设置中设定!

STDOUT_LOGGING标准日志输出

在mybatis核心配置文件中,配置我们的日志!

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

image-20220407183444028

1|06.2、Log4j

什么是Log4j?

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
  • 我们也可以控制每一条日志的输出格式
  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
  1. 先导入log4j的包

    <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
  2. 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/kuang.log log4j.appender.file.MaxFileSize=10mb log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n #日志输出级别 log4j.logger.org.mybatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
  3. 配置log4j为日志的实现

    <settings> <setting name="logImpl" value="LOG4J"/> </settings>
  4. Log4j的使用!测试运行之前的查询

    image-20220407192048240

简单使用

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

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

    static Logger logger = Logger.getLogger(UserMapperTest.class);
  3. 日志界别

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

1|77、分页

思考:为什么要分页?

  • 减少数据的处理量

1|07.1、使用Limit分页

SELECT * FROM mybatis.user LIMIT startIndex,pageSize; SELECT * FROM mybatis.user LIMIT n; #等价于 limit 0,n

使用MyBatis实现分页,核心SQL

  1. 接口

    /** * 分页 * @param map * @return List<User> */ List<User> getUserByLimit(Map<String, Integer> map);
  2. Mapper

    <!--结果集映射--> <resultMap id="UserMap" type="User"> <!--column数据库中的字段,property实体类中的属性--> <result column="pwd" property="password"/> </resultMap> <!--分页--> <select id="getUserByLimit" parameterType="Map" resultMap="UserMap"> select * from mybatis.user limit #{startIndex},#{pageSize}; </select>
  3. 测试

    @Test public void getUserByLimit() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); Map<String, Integer> map = new HashMap<>(); map.put("startIndex",1); map.put("pageSize",2); List<User> userList = mapper.getUserByLimit(map); for (User user : userList) { System.out.println(user); } } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } }

1|07.2、RowBounds分页

不使用SQL实现分页(了解

  1. 接口

    /** * 分页2 * @return List<User> */ List<User> getUserByRowBounds();
  2. Mapper

    <!--分页2--> <select id="getUserByRowBounds" resultMap="UserMap"> select * from mybatis.user; </select>
  3. 测试

    @Test public void getUserByRowBounds() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { //RowBounds实现 RowBounds rowBounds = new RowBounds(1, 2); //通过Java代码层面实现分页 List<User> userList = sqlSession.selectList("com.dt.dao.UserMapper.getUserByRowBounds", null, rowBounds); for (User user : userList) { System.out.println(user); } } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } }

1|07.3、分页插件

image-20220408103607657

了解即可,万一以后公司的架构师,说要使用,你需要知道它是什么东西

1|88、使用注解开发

1|08.1、面向接口编程

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

1|08.2、使用注解开发

  1. 注解在接口上实现

    /** * 注解查询 * @return List<User> */ @Select("select * from user") List<User> getUsers();
  2. 核心配置 mybatis-config.xml

    <!--绑定接口--> <mappers> <mapper class="com.dt.dao.UserMapper"/> </mappers>
  3. 测试

    @Test public void getUsersTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.getUsers(); for (User user : userList) { System.out.println(user); } } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } }

本质:反射机制实现

底层:动态代理!

Mybatis详细执行流程

  1. Resource获取全局配置文件
  2. 实例化SqlsessionFactoryBuilder
  3. 解析配置文件流XMLConfigBuilder
  4. Configration所有的配置信息
  5. SqlSessionFactory实例化
  6. trasactional事务管理
  7. 创建executor执行器
  8. 创建SqlSession
  9. 实现CRUD
  10. 查看是否执行成功
  11. 提交事务
  12. 关闭

在这里插入图片描述

image-20220408141634780

1|08.3、CRUD

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

MyBatisUtils

public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(true); }
  1. 编写接口

    /** * 方法存在多个参数,所有参数的前面必须加上 @Param()注解 * @param id * @return User */ @Select("select * from user where id = #{id}") User getUserById(@Param("id") int id); /** * 注解添加用户 * @param user * @return int */ @Insert("insert into user(id, name, pwd) values(#{id}, #{name}, #{password})") int addUser(User user); /** * 注解修改用户 * @param user * @return int */ @Update("update user set name = #{name}, pwd = #{password} where id = #{id}") int updateUser(User user); /** * 注解删除用户 * @param id * @return int */ @Delete("delete from user where id = #{id}") int deleteUser(@Param("id") int id);
  2. 测试类

    【注意:我们必须要将接口注册绑定到我们的核心配置文件中】

    @Test public void getUserByIdTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); } catch (Exception e) { sqlSession.close(); } finally { sqlSession.close(); } } @Test public void addUserTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.addUser(new User(6, "钱七", "123456")); } catch (Exception e) { sqlSession.close(); } finally { sqlSession.close(); } } @Test public void updateUserTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.updateUser(new User(5, "老六", "111111")); } catch (Exception e) { sqlSession.close(); } finally { sqlSession.close(); } } @Test public void deleteUserTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.deleteUser(6); } catch (Exception e) { sqlSession.close(); } finally { sqlSession.close(); } }

关于@Param()注解

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

#{}和${}区别

  • 2|0{}能防止sql注入

  • MyBatis排序时使用order by 动态参数时需要注意,使用${}而不用#{}

2|19、Lombok

Lombok项目是一个Java库,它会自动插入编辑器和构建工具中,Lombok提供了一组有用的注释,用来消除Java类中的大量样

板代码。仅五个字符(@Data)就可以替换数百行代码从而产生干净,简洁且易于维护的Java类。

使用步骤:

  1. 在IDEA中安装Lombok插件

    image-20220408171745748
  2. 在项目中导入Lombok的jar包

    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</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

    @Data:无参构造,get,set,toString,hashCode,equals

    image-20220408173259303

    在实体类上加注解

    package com.dt.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.ibatis.type.Alias; @Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private String password; }

2|210、多对一处理

多对一:

  • 多个学生,对应一个老师
  • 对于学生而言,关联-多个学生,关联一个老师【多对一】
  • 对于老师而言,集合-一个老师,关联多个学生【一对多】

image-20220408223400179

SQL:

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|010.1、测试环境搭建

  1. 导入Lombok依赖

    <dependencies> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> </dependency> </dependencies>
  2. 新建实体类 Teacher,Student

    Teacher.java

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

    Student.java

    @Data public class Student { private int id; private String name; /** * 学生需要关联一个老师 */ private Teacher teacher; }
  3. 编写实体类对应的Mapper接口【两个】

    TeacherMapper.java

    public interface TeacherMapper { }

    StudentMapper.java

    public interface StudentMapper { }
  4. 编写Mapper接口对应的 mapper.xml配置文件【两个】

    TeacherMapper.xml

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.dt.dao.TeacherMapper"> </mapper>

    StudentMapper.xml

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.dt.dao.StudentMapper"> </mapper>
  5. 在核心配置文件中绑定注册Mapper接口或者文件!【方式很多,随心选】

    mybatis-config.xml

    <mappers> <package name="com.dt.dao"/> </mappers>
  6. 测试查询是否能够成功!

    TeacherMapper.java

    /** * 查询老师 * @param id * @return Teacher */ @Select("select * from teacher where id = #{id}") Teacher getTeacher(@Param("id") int id);

    MyTest.java

    public class MyTest { @Test public void getTeacherTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class); Teacher teacher = mapper.getTeacher(1); System.out.println(teacher); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } } }

1|010.2、按照查询嵌套处理

  1. 给StudentMapper接口增加方法

    /** * 查询所有学生的信息,以及对应的老师信息 * @return List<Student> */ List<Student> getStudent();
  2. 编写对应打的Mapper文件

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.dt.dao.StudentMapper"> <!-- 思路: 1. 查询所有的学生信息 2.根据查询出来的学生的tid,寻找对应的老师! 子查询 --> <select id="getStudent" resultMap="StudentTeacher"> select * from student </select> <resultMap id="StudentTeacher" 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 teacher where id = #{id} </select> </mapper>
  3. 编写完毕去Mybatis配置文件中,注册Mapper

    <mappers> <package name="com.dt.dao"/> </mappers>
  4. 测试

    @Test public void getStudentTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); List<Student> studentList = mapper.getStudent(); for (Student student : studentList) { System.out.println(student); } } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } }
  • 注意点拓展

    <resultMap id="StudentTeacher" type="Student"> <!--association关联属性 property属性名 javaType属性类型 column在多的一方的表中的列名--> <association property="teacher" column="{id=tid,name=tid}" javaType="Teacher" select="getTeacher"/> </resultMap> <!-- 这里传递过来的id,只有一个属性的时候,下面可以写任何值 association中column多参数配置: column="{key=value,key=value}" 其实就是键值对的形式,key是传给下个sql的取值名称,value是片段一中sql查询的字段名。 --> <select id="getTeacher" resultType="teacher"> select * from teacher where id = #{id} and name = #{name} </select>

1|010.3、按照结果嵌套处理

  1. 接口方法编写

    /** * 查询所有学生的信息,以及对应的老师信息 * @return List<Student> */ List<Student> getStudent2();
  2. 编写对应的mapper文件

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.dt.dao.StudentMapper"> <select id="getStudent2" resultMap="StudentTeacher2"> select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid = t.id </select> <resultMap id="StudentTeacher2" type="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <association property="teacher" javaType="Teacher"> <result property="name" column="tname"/> </association> </resultMap> </mapper>
  3. 编写完毕去Mybatis配置文件中,注册Mapper

    <mappers> <package name="com.dt.dao"/> </mappers>
  4. 测试

    @Test public void getStudent2Test() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); List<Student> studentList = mapper.getStudent2(); for (Student student : studentList) { System.out.println(student); } } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } }

小结

  • 按照查询进行嵌套处理就像SQL中的子查询
  • 按照结果进行嵌套处理就像SQL中的联表查询

回顾MySQL多对一查询方式

  • 子查询
  • 联表查询

2|311、一对多处理

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

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

1|011.1、环境搭建

  1. 环境搭建,和刚才一样(跳转到环境搭建

    实体类

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

1|011.2、按结果嵌套处理

  1. TeacherMapper接口编写方法

    /** * 获取指定老师下的所有学生及老师的信息 * @param id * @return Teacher */ Teacher getTeacher(@Param("tid") int id);
  2. 编写接口对应的Mapper配置文件

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.dt.dao.TeacherMapper"> <!--按结果嵌套查询--> <select id="getTeacher" resultMap="TeacherStudent"> select s.id sid,s.name sname,t.name tname,t.id tid from student s,teacher t where s.tid = t.id and t.id = #{tid} </select> <resultMap id="TeacherStudent" type="Teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> <!--复杂的属性,我们需要单独处理 对象:association 集合:collection javaType="" 指定属性的类型 集合中的泛型信息,我们使用ofType获取 --> <collection property="students" ofType="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <result property="tid" column="tid"/> </collection> </resultMap> </mapper>
  3. 将Mapper文件注册到MyBatis-config文件中

    <mappers> <package name="com.dt.dao"/> </mappers>
  4. 测试

    @Test public void getTeacherTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class); Teacher teacher = mapper.getTeacher(1); System.out.println(teacher); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } }

1|011.3、按查询嵌套处理

  1. TeacherMapper接口编写方法

    /** * 获取指定老师下的所有学生及老师的信息 * @param id * @return Teacher */ Teacher getTeacher2(@Param("tid") int id);
  2. 编写接口对应的Mapper配置文件

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.dt.dao.TeacherMapper"> <!--按查询嵌套查询--> <select id="getTeacher2" resultMap="TeacherStudent2"> select * from teacher where id = #{tid} </select> <resultMap id="TeacherStudent2" type="Teacher"> <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/> </resultMap> <select id="getStudentByTeacherId" resultType="Student"> select * from student where tid = #{tid} </select> </mapper>
  3. 将Mapper文件注册到MyBatis-config文件中

    <mappers> <package name="com.dt.dao"/> </mappers>
  4. 测试

    @Test public void getTeacher2Test() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class); Teacher teacher = mapper.getTeacher2(1); System.out.println(teacher); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } }

小结

  1. 关联-association【多对一】
  2. 集合-collection【一对多】
  3. javaType & ofType
    1. JavaType用来指定实体类中属性的类型
    2. ofType 用来指定映射到List或者集合中的POJO类型

注意点

  • 保证SQL的可读性,尽量保证通俗易懂
  • 注意一对多和多对一中,属性和字段对应的问题
  • 如果问题不好排查,可以使用日志【推荐使用Log4j】

2|412、动态SQL

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

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

使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis 显著地提升了这一特性的易用性。

如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。

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

1|012.1、搭建环境

新建一个数据库表:blog

字段:id,title,author,create_time,views

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

创建一个基础工程

  1. 导包

  2. 编写核心配置文件,设置下划线驼峰自动转换

    <?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核心配置文件--> <configuration> <!--引入外部配置文件--> <properties resource="db.properties"/> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> <!--是否开启驼峰命名自动映射--> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!--可以给实体类取别名--> <typeAliases> <package name="com.dt.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.dt.dao"/> </mappers> </configuration>
  3. 编写实体类

    @Data public class Blog { private String id; private String title; private String author; private Date createTime; private int views; }
  4. 编写实体类对应的Mapper接口 和 Mapper.xml文件

    public interface BlogMapper { }
    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.dt.dao.BlogMapper"> </mapper>
  5. 编写IDUtils工具类

    public class IDUtils { public static String getId() { return UUID.randomUUID().toString().replace("-", ""); } }
  6. 插入初始数据

    编写接口及它的xml文件

    /** * 插入数据 * @param blog * @return int */ int addBlog(Blog blog);
    <insert id="addBlog" parameterType="Blog"> insert into mybatis.blog (id, title, author, create_time, views) values (#{id}, #{title}, #{author}, #{createTime}, #{views}); </insert>

    初始化博客方法

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

1|012.2、If

需求:根据作者名字和博客名字来查询博客!如果作者名字不为空,就根据作者名字来查询。如果博客名字不为空,就根据博客名字来查询。如果二者都为空,那就把表的所有内容都查询出来

  1. 编写接口

    /** * 查询博客 * @param map * @return List<Blog> */ List<Blog> queryBlogIf(Map map);
  2. 编写xml文件的SQL语句

    <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>
  3. 测试

    @Test public void queryBlogIfTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); HashMap map = new HashMap(); map.put("author", "狂神说"); map.put("title", "Java如此简单"); List<Blog> blogs = mapper.queryBlogIf(map); for (Blog blog : blogs) { System.out.println(blog); } } catch (Exception e) { sqlSession.close(); } }

1|012.3、where

修改上面的SQL语句

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

这个where标签会知道如果它包含的标签中有返回值的话,它就插入一个where。此外,如果标签返回的内容是以AND

OR 开头的,则它会剔除掉。

1|012.4、choose (when, otherwise)

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

  1. 编写接口

    /** * 查询博客 * @param map * @return List<Blog> */ List<Blog> queryBlogChoose(Map map);
  2. 编写xml文档的SQL语句

    <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>
  3. 测试

    @Test public void queryBlogChooseTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); HashMap map = new HashMap(); //map.put("author", "狂神说"); //map.put("title", "Java如此简单"); map.put("views", 1000); List<Blog> blogs = mapper.queryBlogChoose(map); for (Blog blog : blogs) { System.out.println(blog); } } catch (Exception e) { sqlSession.close(); } }

补充

  • MyBatis 提供了 choose 元素。if标签是与(and)的关系,而 choose 是或(or)的关系。

  • choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default

1|012.5、Set

  1. 编写接口

    /** * 更新博客 * @param map * @return int */ int updateBlog(Map map);
  2. 编写xml文档的SQL语句

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

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

  3. 测试

    @Test public void updateBlogTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); HashMap map = new HashMap(); map.put("title", "Python如此简单"); map.put("author", "Dt"); map.put("id", "8b525e54a01c4aebb0ef5cb69969538d"); mapper.updateBlog(map); } catch (Exception e) { sqlSession.close(); } }

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

1|012.6、trim

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

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

prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。

同理,set 元素等价的自定义 trim 元素

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

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

1|012.7、SQL片段

有的时候,我们可能会将一些功能的部分抽取出来,方便复用

提取SQL片段:

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

引用SQL片段:

<select id="queryBlogIf" parameterType="Map" resultType="Blog"> select * from mybatis.blog <where> <include refid="if-title-author"/> </where> </select>

注意点:

  • 最好基于 单表来定义 sql 片段,提高片段的可重用性
  • 在 sql 片段中不要包括 where

1|012.8、Foreach

  • 动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)

  • foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!

  • 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

需求:我们需要查询 blog 表中 id 分别为1,2,3的博客信息

  1. 编写接口

    /** * 查询第1-2-3号记录的博客 * @param map * @return List<Blog> */ List<Blog> queryBlogForeach(Map map);
  2. 编写xml文档的SQL语句

    <select id="queryBlogForeach" parameterType="Map" resultType="Blog"> select * from blog <where> <!-- collection:指定输入对象中的集合属性 item:每次遍历生成的对象 open:开始遍历时的拼接字符串 close:结束时拼接的字符串 separator:遍历对象之间需要拼接的字符串 select * from blog where id in (1,2,3) --> <foreach collection="ids" item="id" open="id in (" separator="," close=")"> #{id} </foreach> </where> </select>
  3. 测试

    @Test public void queryBlogForeachTest() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); HashMap map = new HashMap(); ArrayList<Integer> ids = new ArrayList<>(); ids.add(1); ids.add(2); ids.add(3); map.put("ids", ids); List<Blog> blogs = mapper.queryBlogForeach(map); for (Blog blog : blogs) { System.out.println(blog); } } catch (Exception e) { sqlSession.close(); } }

小结

其实动态 sql 语句的编写往往就是一个拼接的问题,为了保证拼接准确,我们最好首先要写出原生的 sql 语句,然后改成通用的 mybatis 动态sql ,防止出错。

2|513、缓存

1|013.1、简介

  1. 什么是缓存[Cache]?
    • 存在内存中的临时数据
    • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库查询文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
  2. 为什么使用缓存?
    • 减少和数据库的交互次数,减少系统开销,提高系统效率
  3. 什么样的数据能使用缓存
    • 经常查询并且不经常改变的数据

1|013.2、Mybatis缓存

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

1|013.3、一级缓存

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

测试步骤:

  1. 开启日志

    <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings>
  2. 编写接口

    /** * 根据id查询指定用户 * @param id * @return User */ User queryUserById(@Param("id") int id);
  3. 编写接口对应的Mapper的SQL语句

    <select id="queryUserById" resultType="User"> select * from mybatis.user where id = #{id} </select>
  4. 测试

    public class MyTest { @Test public void queryUserById() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user1 = mapper.queryUserById(1); System.out.println(user1); System.out.println("========================="); User user2 = mapper.queryUserById(1); System.out.println(user2); System.out.println(user1==user2); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } } }
  5. 查看日志输出

    image-20220410171319606

    通过日志可以看出第二次没有执行SQL查询语句,是直接从一级缓存中获取数据

1|0一级缓存失效的四种情况

  1. SqlSession相同,查询条件不同

    @Test public void queryUserById() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user1 = mapper.queryUserById(1); System.out.println(user1); System.out.println("========================="); User user2 = mapper.queryUserById(2); System.out.println(user2); System.out.println(user1==user2); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } }

    image-20220410172214683

    结果:通过日志看出,发送了两条SQL语句

    存在缓存中查询不到的数据,会刷新缓存

  2. SqlSession相同,两次查询之间进行了增删改操作

    1. 编写接口

      /** * 修改用户 * @param user * @return int */ int updateUser(User user);
    2. 编写接口对应的Mapper的SQL语句

      <update id="updateUser" parameterType="User"> update mybatis.user <set> <if test="name != null">name = #{name},</if> <if test="pwd != null">pwd = #{pwd}</if> </set> where id = #{id} </update>
    3. 测试

      @Test public void queryUserById() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user1 = mapper.queryUserById(1); System.out.println(user1); System.out.println("========================="); mapper.updateUser(new User(2, "罗翔", null)); System.out.println("========================="); User user2 = mapper.queryUserById(1); System.out.println(user2); System.out.println(user1==user2); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } }
    4. 查看日志输出

      image-20220410183105314

    结果:通过日志看出,发送了三条SQL语句

    增删改操作,可能会改变原来的数据,所以一定会刷新缓存

  3. SqlSession不同,查询条件相同

    @Test public void queryUserById() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); SqlSession sqlSession1 = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class); User user1 = mapper.queryUserById(1); System.out.println(user1); System.out.println("========================="); User user2 = mapper1.queryUserById(1); System.out.println(user2); System.out.println(user1==user2); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); sqlSession1.close(); } }

    image-20220410191700262

    结果:通过日志看出,发送了两条SQL语句

    每个SQLSession的缓存相互独立

  4. SqlSession相同,查询条件相同,手动清理缓存

    @Test public void queryUserById() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); try { UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user1 = mapper.queryUserById(1); System.out.println(user1); //手动清理缓存 sqlSession.clearCache(); System.out.println("========================="); User user2 = mapper.queryUserById(1); System.out.println(user2); System.out.println(user1==user2); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } }

    image-20220410184650831

    结果:通过日志看出,发送了两条SQL语句

小结

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

一级缓存失效情况:没有使用到当前的一级缓存,效果就是,还需要再向数据库中发起一次查询请求!

一级缓存相当于一个Map

1|013.4、二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
  • 工作机制
    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
    • 新的会话查询信息,就可以从二级缓存中获取内容
    • 不同的mapper查出的数据会放在自己对应的缓存(map)中

使用步骤:

  1. 在核心配置文件中开启全局缓存

    <settings> <!--显示的开启全局缓存--> <setting name="cacheEnabled" value="true"/> </settings>
  2. 所有的实体类先实现序列化接口(提示:cache标签中的readonly属性等于 false 才需要序列化)

    @Data @AllArgsConstructor @NoArgsConstructor public class User implements Serializable { private int id; private String name; private String pwd; }
  3. 去每个mapper.xml中配置使用二级缓存,这个配置非常简单

    <!--在当前Mapper.xml中使用二级缓存--> <cache/>

    官方自定义参数

    <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/> <!--这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突-->

    可用的清除策略有:

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

    默认的清除策略是 LRU。

    flushInterval(刷新间隔)属性可以被设置为任意的正整数,设置的值应该是一个以毫秒为单位的合理时间量。 默认情况是不设置,也就是没有刷新间隔,缓存仅仅会在调用语句时刷新。

    size(引用数目)属性可以被设置为任意正整数,要注意欲缓存对象的大小和运行环境中可用的内存资源。默认值是 1024。

    readOnly(只读)属性可以被设置为 true 或 false。只读的缓存会给所有调用者返回缓存对象的相同实例。 因此这些对象不能被修改。这就提供了可观的性能提升。而可读写的缓存会(通过序列化)返回缓存对象的拷贝。 速度上会慢一些,但是更安全,因此默认值是 false。

    提示 二级缓存是事务性的。这意味着,当 SqlSession 完成并提交时,或是完成并回滚,但没有执行 flushCache=true 的 insert/delete/update 语句时,缓存会获得更新

  4. 测试

    @Test public void queryUserById() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); SqlSession sqlSession1 = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class); User user1 = mapper.queryUserById(1); System.out.println(user1); sqlSession.close(); System.out.println("========================="); User user2 = mapper1.queryUserById(1); System.out.println(user2); System.out.println(user1==user2); sqlSession1.close(); }

    image-20220410192759920

    结果:通过日志看出,不同的SqlSession只发送了一条SQL语句

    正好符合以下特性

    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中。
    • 新的会话查询信息,就可以从二级缓存中获取内容

前提:必须在同一个Mapper中,二级缓存只针对一个namespace

小结

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

1|013.5、缓存原理图

缓存顺序:

  1. 先去二级缓存中查找
  2. 再去一级缓存中查找
  3. 最后再查询数据库

img

1|013.6、自定义缓存-Ehcache(了解即可)

Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存

要在程序中使用ehcache,先要导包

<dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.1.0</version> </dependency>

在mapper中指定使用我们的ehcache缓存实现

<!--在当前Mapper.xml中使用二级缓存--> <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

配置文件

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>

目前:Redis来做缓存 K-V


__EOF__

本文作者userName
本文链接https://www.cnblogs.com/dt746294093/p/16768030.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   D..T  阅读(51)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
点击右上角即可分享
微信分享提示