> 技术文档 > 破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践录

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践录


一、什么是 MyBatis

        通过 MyBatis中文网站 我们了解到 “MyBatis 是一款优秀的持久层框架 ” ,用于简化JDBC的开发,而此处 “ 持久层 ” :指的是持久化操作的层,通常指数据访问层(Dao),用来操作数据库

        换句话说,MyBatis 是更简单的完成程序与数据库交互的框架,即更简单方便地操作和读取数据库工具

二、 MyBatis 入门

2.1、创建项目

        创建 Spring Boot 项目,并导入 MyBatis 启动依赖和 MySQL 驱动包

        创建用户表,并创建对对应的实体类 UserInfo

@Datapublic class UserInfo { private Integer id; private String username; private String password; private Integer age; private Integer gender; private String phone; private Integer deleteFlag; private Date createTime; private Date updateTime;}

        数据库规范:全部小写,单词之间用下划线分割( _ )

        Java规范:   属性使用小驼峰来表示

        注意:我们创建表和实体类中,要把数据库字段和Java属性一一对应起来 

2.2、配置数据库连接字符串

        在 application.yml 配置文件中配置如下:


 2.3、入门操作

        MyBatis 采用 “ 接口+XML/注解 ” 的方式实现数据访问层,实现了接口与实现的分离,其核心机制为:在运行时为接口生成动态代理对象,即自动创建它的实现类,能够轻松创建mock实现进行单元测试

         MyBatis 在运行时通过 ​​动态代理(Dynamic Proxy)​​ 机制自动生成了接口的实现类

我们接下来查询所有用户

@Mapperpublic interface UserInfoMapper { @Select(\"SELECT * from user_info\") List selectAll();}

        @Mapper注解标识该接口为 MyBatis 的 Mapper 接口

        •  运行时框架会自动生成接口代理对象,并交由 Spring IOC 容器管理

        •  @Select 注解:用于标记查询方法,定义对应 SQL 查询语句

2.4、单元测试 

        测试类已在 src/test 目录下自动生成,可直接用于测试

@SpringBootTestclass UserInfoMapperTest { @Autowired private UserInfoMapper userInfoMapper; @Test void selectAll() { List userInfos = userInfoMapper.selectAll(); System.out.println(userInfos); }}

        在该测试类上添加了 @SpringBootTest 注解后,运行时将自动加载 Spring 运行环境方法加上@Test 注解后,该方法即可单独运行;通过@Autowired 注解注入待测试的类后,即可开始进行测试

        运行结果:成功查询了所有用户的信息

 三、MyBatis基础操作(增删改查)

3.1、配置日志

        在MyBatis中我们可以借助日志,查看SQL语句的执行,传递的参数以及执行的结果,在application.yml 配置文件中配置(properties文件配置查阅前篇)

mybatis: configuration: # 配置打印 MyBatis⽇志 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

        配置后可以看到

3.2、参数传递

         查询 ID 为 3 的用户

@Mapperpublic interface UserInfoMapper { @Select(\"select username,password,age,gender,phone from user_info where id = #{id}\") UserInfo selectById(Integer id);}

        当 Mapper 接口方法的形参仅有一个普通类型参数时,# {...} 中的属性名称可以任意指定,但是如果形参有多个普通类型的参数时,属性名称必须对应(见3.3例中代码)

        生成测试用例:#{id}

@Test void selectById() { UserInfo userInfo = userInfoMapper.selectById(3); System.out.println(userInfo); }

        查询结果: 

        可通过@Param 注解设置参数别名。若使用 @Param 设置别名,#{...} 中的属性名必须与 @Param 指定的别名保持一致

 @Select(\"select username,password,age,gender,phone from user_info where id = #{userID}\") UserInfo selectById(@Param(\"userID\") Integer id);

 ⚠️注意:

 @Select(\"SELECT * from user_info\") List selectAll(); @Select(\"select username,password,age,gender,phone from user_info where id = #{userID}\") UserInfo selectById(@Param(\"userID\") Integer id); @Select(\"select username,password,age,gender,phone from user_info where age = #{age}\") List selectAllByAge(Integer age);

3.3、增(Insert) 

        目标SQL语句:

        插入另一条数据,并将SQL中的常量替换成动态的参数:

@Insert(\"insert into user_info (username, password, age, gender, phone) values (#{username}, #{password}, #{age}, #{gender}, #{phone})\") Integer insert(UserInfo userInfo);
 @Test void insert() { UserInfo userInfo = new UserInfo(); userInfo.setUsername(\"楚子航\"); userInfo.setPassword(\"123456\"); userInfo.setGender(1); userInfo.setAge(19); userInfo.setPhone(\"122222222222\"); int result=userInfoMapper.insert(userInfo); System.out.println(\"影响的行数\"+result); }

        在 MyBatis 中,insert() 方法返回的结果和在MySQL中返回的结果是一样的,都是返回影响的行数,观察测试结果:

 返回主键

        我们想在插入之后,拿到刚刚插入的数据ID 

@Options(useGeneratedKeys = true,keyProperty = \"id\") @Insert(\"insert into user_info (username, password, age, gender, phone) values (#{username}, #{password}, #{age}, #{gender}, #{phone})\") Integer insert(UserInfo userInfo);
 @Test void insert() { UserInfo userInfo = new UserInfo(); userInfo.setUsername(\"路鸣泽\"); userInfo.setPassword(\"123456\"); userInfo.setGender(1); userInfo.setAge(16); userInfo.setPhone(\"11111111111\"); int result=userInfoMapper.insert(userInfo); System.out.println(\"影响的行数\"+result+\" id:\"+userInfo.getId()); }

        • useGeneratedKeys:启用后,MyBatis 将调用 JDBC 的 getGeneratedKeys 方法来获取数据库自动生成的主键(如 MySQL 和 SQL Server 中的自增字段),默认值为 false
        • keyProperty:指定用于标识对象的唯一属性,MyBatis 会通过 getGeneratedKeys 的返回值或 insert 语句的 selectKey 子元素为其赋值

注意:

        设置 useGeneratedKeys=true 后,方法返回值仍是受影响的行数,自增 ID 会被自动赋给 keyProperty 指定的属性

3.4、删(delete)

         将上述SQL中的常量替换为动态参数

@Delete(\"delete from user_info where id = #{id}\") void deleteById(Integer id);
 @Test void deleteById() { userInfoMapper.deleteById(9); }

        观察运行结果发现Id为 9 的数据已被删除

 3.5、改(update)

        将上述SQL中的常量替换为动态参数

 @Update(\"update user_info set username = #{username} where id = #{id}\") void updateById(UserInfo userInfo);
 @Test void updateById() { UserInfo userInfo = new UserInfo(); userInfo.setId(5); userInfo.setUsername(\"喜羊羊\"); userInfoMapper.updateById(userInfo); }

        观察运行结果发现Id为 5 的数据名称已经更改为喜羊羊了

3.6、查(select)

        我们再次查询所有信息

 @Select(\"select id,username,password,age,gender,phone,delete_flag,create_time,update_time from user_info\") List selectById();
 @Test void selectById() { List userInfoList = userInfoMapper.selectById(); System.out.println(userInfoList); }

        从运行结果可以看出,SQL语句中查询了 delete_flag、create_time 和 update_time 字段,但这些字段并未被赋值

        为什么呢? 这时我们会想到是不是 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 selectById();

        运行结果:

MyBatis在自动映射查询结果时,会按以下步骤处理:

  1. 获取查询结果返回的列名
  2. 在目标Java类中查找名称匹配的属性(不区分大小写)
  3. 当列名与属性名匹配时(例如数据库列\"ID\"对应Java属性\"id\"),自动将列值映射到对应属性

 解决方法

3.6.1、起别名

        如上猜测,将数据库字段名称通过起别名的方法与Java属性名称保持一致,另外我们从下方代码可见SQL语句可以用 + 连接 

 @Select(\"select id,username,password,age,gender,phone,\" + \"delete_flag as deleteflag,create_time as createtime,update_time as updatetime \" + \"from user_info\") List selectById();
3.6.2、结果映射

        @Results 注解用于建立数据库字段与 Java 对象属性之间的映射关系,它包含一个由 @Result 元素组成的数组,其中每个元素通过 column 指定数据库列名,property 指定对应的 Java 属性名,从而实现二者之间的映射关联

 @Results({ @Result(column = \"delete_flag\",property = \"deleteFlag\"), @Result(column = \"create_time\",property = \"createTime\"), @Result(column = \"update_time\",property = \"updateTime\") }) @Select(\"select id,username,password,age,gender,phone,delete_flag,create_time,update_time from user_info\") List selectResult();

        现在的问题是:我们上述代码实现了众多增删改查方法,每个方法进行结果映射都需要字段复制操作,如果其他方法涉及不同的数据库字段,来回修改会非常不便。在Aokey看来,这并不比使用别名便利

        针对这种情况,我们可以通过 Id 属性为 Results 定义别名,然后使用 @ResultMap 注解来复用其他已经定义的 ResultMap 配置

3.6.3、 配置驼峰自动转换

        在 application.yml 配置文件中配置如下:

mybatis: configuration: map-underscore-to-camel-case: true #配置驼峰⾃动转换
 @Select(\"select id,username,password,age,gender,phone,delete_flag,create_time,update_time from user_info where age = #{age}\") List selectAllByAge(Integer age);

        查询结果: