目录
[一、什么是 MyBatis?](#一、什么是 MyBatis?)
[二、MyBatis 入门](#二、MyBatis 入门)
[2.1 准备工作](#2.1 准备工作)
[2.2 配置数据库连接](#2.2 配置数据库连接)
[2.3 编写持久层的代码:](#2.3 编写持久层的代码:)
[三、MyBatis 基础操作](#三、MyBatis 基础操作)
[3.1 打印日志](#3.1 打印日志)
[3.2 参数传递](#3.2 参数传递)
[3.3 增加 (Insert)](#3.3 增加 (Insert))
[3.4 删(Delete)](#3.4 删(Delete))
[3.5 改(Update)](#3.5 改(Update))
[3.6 查(Select)](#3.6 查(Select))

一、什么是 MyBatis?
MyBatis 是一款优秀的持久层框架,用于简化 JDBC 的开发。
-
它本是 Apache 的开源项目 iBatis,2010 年迁移到 Google Code 并改名为 MyBatis,2013 年迁移到 GitHub。
-
所谓持久层,指的就是持久化操作的层,通常指数据访问层(Dao),用来操作数据库。
-
简单来说,MyBatis 是更简单完成程序和数据库交互的框架,也就是更简单的操作和读取数据库的工具。
二、MyBatis 入门
MyBatis 操作数据库的步骤:
-
准备工作(创建 SpringBoot 工程、数据库表准备、实体类)
-
引入 MyBatis 相关依赖,配置数据库连接信息
-
编写 SQL 语句(注解/XML)
-
测试
2.1 准备工作
创建工程:创建 SpringBoot 工程,并导入 MyBatis 起步依赖和 MySQL 驱动包。
XML
<!-- Source: https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.19</version>
<scope>compile</scope>
</dependency>
<!-- Source: https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
<scope>compile</scope>
</dependency>
2.2 配置数据库连接
在 application.yml 中配置:
XML
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
2.3 编写持久层的代码:
java
@Mapper
public interface UserInfoMapper {
@Select("select username, `password`, age, gender, phone from user_info")
List<UserInfo> queryAllUser();
}
@Mapper 注解: 表示这是 Mybatis 的 Mapper 的接口,运行的时候会自动生成类对象,并交给 Spring 的 IOC 容器管理。
@Select 注解:代表是 Select 查询,注解内容是 select 的 sql
@Insert 注解:代表是 insert 插入,注解内容是 insert 的 sql
@Update 注解:代表是 update 修改,注解内容是 update 的 sql
@Delete 注解:代表是 delete 删除,注解内容是 delete 的 sql
三、MyBatis 基础操作
3.1 打印日志
在配置文件中开启 MyBatis 日志,可以查看 SQL 执行,参数传递和执行结果,yml格式为:
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
3.2 参数传递
使用 #{} 获取方法中的参数:
java
@Select("select username, `password`, age, gender, phone from user_info where id= #{id}")
UserInfo queryById(Integer id);
特例:如果方法只有一个普通类型的参数,#{} 里面的属性名可以随便写,建议和参数名保持一致。可以通过 @Param 设置参数别名:
java
@Select("select username, `password`, age, gender, phone from user_info where id= #{userid}")
UserInfo queryById(@Param("userid") Integer id);
3.3 增加 (Insert)
java
@Insert("insert into user_info (username, `password`, age, gender, phone) " +
"values (#{username},#{password},#{age},#{gender},#{phone})")
Integer insert(UserInfo userInfo);
返回主键:如果需要获取新插入数据的自增id,需要添加 @Options 注解
java
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
@Insert("insert into user_info (username, age, gender, phone) " +
"values (#{userInfo.username},#{userInfo.age},#{userInfo.gender},#{userInfo.phone})")
Integer insert(@Param("userInfo") UserInfo userInfo);
- useGeneratedKeys:令 Mybatis 使用 JDBC 的 getGeneratedKeys 方法取出数据库内部生成的主键。
- keyProperty:java实体类中接收主键的属性名,把数据库生成的主键值,注入到实体对象的这个字段上。
- keyColumn:数据库表中的主键列名,告诉MyBatis,数据库表返回的主键是哪一列
3.4 删(Delete)
java
@Delete("delete from user_info where id = #{id}")
void delete(Integer id);
3.5 改(Update)
java
@Update("update user_info set username=#{username} where id=#{id}")
void update(UserInfo userInfo);
3.6 查(Select)
查询的时候,只有 Java 对象属性和数据库字段一模一样的时候,才会进行赋值。
Java对象使用驼峰命名方式,数据库字段使用蛇形命名方式,这两者就对应不上,如何解决。
解决方法:
1.起别名 :在 SQL中给列明起别名,保持与实体类属性名一致。
java
@Select("select id, username, `password`, age, gender, phone, delete_flag as deleteFlag, " +
"create_time as createTime, update_time as updateTime from user_info")
List<UserInfo> queryAllUser();
2.结果映射 : 使用 @Results 注解
java
@Select("select id, username, `password`, age, gender, phone, delete_flag, " +
"create_time, update_time from user_info")
@Results({
@Result(column = "delete_flag", property = "deleteFlag"),
@Result(column = "create_time", property = "createTime"),
@Result(column = "update_time", property = "updateTime")
})
List<UserInfo> queryAllUser();
如果其他 SQL 也希望复用这个映射关系,可以给 Result 定义名称:
这里就把下面的映射关系的名字定义为 resultMap,然后通过 @ResultMap(value = "resultMap") 来复用
java
@Results(id = "resultMap", value = {
@Result(column = "delete_flag", property = "deleteFlag"),
@Result(column = "create_time", property = "createTime"),
@Result(column = "update_time", property = "updateTime")
})
3.开启驼峰自动转换(推荐):
java
mybatis:
configuration:
map-underscore-to-camel-case: true
驼峰命名规则: abc_xyz => abcXyz。表中字段用蛇形命名发,Java 属性用驼峰命名发,开启这个配置之后自动映射。