MyBatis 的介绍

MyBatis 的核心组件

  • SqlSessionFactory:用于创建 SqlSession 的工厂类
  • SqlSession:MyBatis 的核心组件,用于向数据库执行 SQL
  • 主配置文件:XML 配置文件,可以对 MyBatis 的底层行为做出详细的配置
  • Mapper 接口
  • Mapper 映射文件:用于编写 SQL,并将 SQL 和 实体类映射,采用 XML、注解均可实现

每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。
SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。
而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。

TransactionManager:事务管理器,它决定事务作用域和控制方式。

MyBatis 整合 SpringBoot

  1. 添加依赖 mybatis-spring-boot-starter
  2. 在 application.yml 中配置 数据源信息 (datasource)
  3. 在 application.yml 中配置 MyBaits 属性
  4. 编写 Mapper 接口,标注 @Mapper 注解,或者在启动类上使用

@MapperScan(value = "com.hfy.community.mapper") value 为 Mapper 接口所在包的路径

  1. 编写 Mapper 接口的 XML 映射文件(可选步骤,接口名称 与 映射文件名称需保持一致,否则报错) ```yaml mybatis: mapper-locations: classpath:mybatis/mybatis/*.xml configuration:

    输出执行的 SQL 语句

    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl use-generated-keys: true

    开启驼峰命名自动映射

    map-underscore-to-camel-case: true

    config-location: classpath:mybatis/mybatis-config.xml

config-location 用来指定 MyBaits 的配置文件位置

在配置文件中可以进行的操作,在 application.yml 中也能进行 比如上面的 use-generated-keys

  1. ```xml
  2. <?xml version="1.0" encoding="UTF-8" ?>
  3. <!DOCTYPE mapper
  4. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  5. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  6. <mapper namespace="com.hfy.community.mapper.UserMapper">
  7. <select id="selectId" resultType="integer" >
  8. select `id` from `user` where `username` = #{username}
  9. </select>
  10. </mapper>

探究 XML 映射文件

MyBatis 中 # 和 $ 的区别

MySQL 预处理
PrepareStatement 的用法
#{ } 和 ${ } 的底层都是调用的 prepareStatement()
但是 #{key} 会将 key 的值作为数据部分替换掉占位符,
而 ${key} 只是将 key 的值原样输入。


{ }:表示占位符,不会发生 SQL 注入攻击。
通过 #{ } 可以设置值并自动进行 Java 和 JDBC 的类型转换

  1. <select id="selectId" resultType="integer">
  2. select `id` from `user` where `username` = #{value}
  3. </select>
Connection connection = dataSource.getConnection();

PreparedStatement preparedStatement
    = connection.prepareStatement("select `id` from `user` where `username` = ? ");
preparedStatement.setString(1, "admin");

ResultSet resultSet = preparedStatement.executeQuery();

${ }:表示拼接符,会发生 SQL 注入攻击。
传入的内容拼接在 SQL 中且不进行 Java 和 JDBC 的类型转换

<select id="selectId" resultType="integer">
    select `id` from `user` where `username` = '${username}'
</select>
Connection connection = dataSource.getConnection();

PreparedStatement preparedStatement
    = connection.prepareStatement("select `id` from `user` where `username` = 'admin'");

ResultSet resultSet = preparedStatement.executeQuery();