当前位置: 首页 > news >正文

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

一、什么是 MyBatis

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

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

二、 MyBatis 入门

2.1、创建项目

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

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

@Data
public 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)​​ 机制自动生成了接口的实现类

我们接下来查询所有用户

@Mapper
public interface UserInfoMapper {@Select("SELECT * from user_info")List<UserInfo> selectAll();
}

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

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

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

2.4、单元测试 

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

@SpringBootTest
class UserInfoMapperTest {@Autowiredprivate UserInfoMapper userInfoMapper;@Testvoid selectAll() {List<UserInfo> 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 的用户

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

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

        生成测试用例:#{id}

@Testvoid 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<UserInfo> 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<UserInfo> 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);
 @Testvoid 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);
    @Testvoid 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);
 @Testvoid deleteById() {userInfoMapper.deleteById(9);}

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

 3.5、改(update)

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

    @Update("update user_info set username = #{username} where id = #{id}")void updateById(UserInfo userInfo);
    @Testvoid 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<UserInfo> selectById();
    @Testvoid selectById() {List<UserInfo> 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<UserInfo> 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<UserInfo> 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<UserInfo> 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<UserInfo> selectAllByAge(Integer age);

        查询结果:

http://www.dtcms.com/a/305616.html

相关文章:

  • Cockpit管理服务器
  • 通达OA服务器无公网IP网络,如何通过内网穿透实现外网远程办公访问OA系统
  • 记录Linux下ping外网失败的问题
  • Docker学习其一
  • 【机器学习】pycharm使用SSH SFTP 远程连接 ubuntu服务器 进行开发+调试+数据训练
  • 在VS2022中调试ASP.NET项目时修改DLL或ASPX动态页面的原理及实现方法
  • 【推荐100个unity插件】Unity 创意编程库——Klak插件的使用
  • 计算机网络基础(二) --- TCP/IP网络结构(应用层)
  • 论文Review LSLAM BALM | 经典激光SLAM方案!港大MARS出品!RAL2021 | 激光BA优化
  • DIV 指令概述
  • AWS VPC NAT 网关可观测最佳实践
  • 【iOS】weak修饰符
  • 计算机组成原理(6) - 加法器
  • SpringBoot学习 |springboot概念+微服务架构
  • 【AI】入门级提示词模板:适用于ChatGPT、文心一言等主流模型
  • day25——HTML CSS 前端开发
  • 运维管理系统的优势和缺点
  • springcloud03-Nacos配置中心
  • HTML应用指南:利用POST请求获取全国公牛门店位置信息
  • Python 使用 asyncio 包处理并 发(使用asyncio包编写服务器)
  • WebSocket 简介与在 Vue 中的使用指南
  • LaTeX 创建工程并生成完整文档指南
  • tplink er2260t配置带vlan的pppoe拨号
  • 【人工智能99问】混合专家模型(MoE)是如何训练的?(18/99)
  • Tomcat 服务器日志
  • uvm-tlm-sockets
  • 论文Review 3DGSSLAM S3PO-GS | ICCV 2025 港科广出品!| 高效快速的3DGSSLAM!
  • 适配鸿蒙低性能设备的终极优化方案:从启动到渲染全链路实战
  • 企业级web应用服务器TOMCAT
  • Qt 嵌入式系统资源管理