MyBatis 入门:从 JDBC 到优雅操作数据库(一)

目录

[一、什么是 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 操作数据库的步骤:

  1. 准备工作(创建 SpringBoot 工程、数据库表准备、实体类)

  2. 引入 MyBatis 相关依赖,配置数据库连接信息

  3. 编写 SQL 语句(注解/XML)

  4. 测试

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 属性用驼峰命名发,开启这个配置之后自动映射。

相关推荐
晓梦林3 小时前
BUUCTF-菜刀流量-MISC-学习笔记
笔记·学习
这个DBA有点耶18 小时前
库内计算推理:一条SQL背后的算子融合,和外挂方案差了几次网络往返
数据库·人工智能·sql
SL_staff19 小时前
JVS-BI 实战:业务人员如何用零代码 ELT + 可视化配置构建实时经营分析闭环
java·spring·全栈
David猪大卫20 小时前
【C++修炼】map 和 set 的使用
c语言·开发语言·数据结构·c++·经验分享·笔记·学习
星恒随风20 小时前
MySQL 从零入门(三):表的约束详解
linux·服务器·数据库·笔记·mysql
nice_lcj52021 小时前
【从零理解 Spring AI · 12】MCP 的两种角色:做客户端还是做服务端
java·后端·spring·spring ai·ai应用开发
蒸蒸yyyyzwd1 天前
从后端面经学到的 3 个知识
笔记·学习
17岁的勇气1 天前
Unity Shader unity文档学习笔记(二十二):shader变体
笔记·学习·unity
杨凯凡1 天前
Spring Framework 7 HTTP Interface 实战:声明式 RestClient、超时与测试
java·spring·http
坤坤子吖1 天前
Linux网络编程:自定义应用层协议与 JSON 序列化
linux·服务器·网络·c++·笔记·json