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
- 添加依赖
mybatis-spring-boot-starter - 在 application.yml 中配置 数据源信息 (datasource)
- 在 application.yml 中配置 MyBaits 属性
- 编写 Mapper 接口,标注 @Mapper 注解,或者在启动类上使用
@MapperScan(value = "com.hfy.community.mapper") value 为 Mapper 接口所在包的路径
- 编写 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: trueconfig-location: classpath:mybatis/mybatis-config.xml
config-location 用来指定 MyBaits 的配置文件位置
在配置文件中可以进行的操作,在 application.yml 中也能进行 比如上面的 use-generated-keys
```xml<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.hfy.community.mapper.UserMapper"><select id="selectId" resultType="integer" >select `id` from `user` where `username` = #{username}</select></mapper>
探究 XML 映射文件
MyBatis 中 # 和 $ 的区别
MySQL 预处理
PrepareStatement 的用法
#{ } 和 ${ } 的底层都是调用的 prepareStatement() ,
但是 #{key} 会将 key 的值作为数据部分替换掉占位符,
而 ${key} 只是将 key 的值原样输入。
{ }:表示占位符,不会发生 SQL 注入攻击。
通过 #{ } 可以设置值并自动进行 Java 和 JDBC 的类型转换
<select id="selectId" resultType="integer">select `id` from `user` where `username` = #{value}</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();
