查看: 389|回复: 1

Spring Boot 3整合MyBatis和Druid实现会计记账表CRUD实例

[复制链接]
发表于 5 天前 | 显示全部楼层 |阅读模式
随着Spring Boot 3的发布,许多开发者开始将项目升级至此版本。本文通过一个会计记账表(accounting)的增删改查示例,演示如何在Spring Boot 3中整合MyBatis和Druid数据源。

环境要求:JDK 17+、Spring Boot 3.x。

1. 添加项目依赖
在pom.xml中引入核心依赖:
  1. <!-- Spring Boot Starter Web -->
  2. <dependency>
  3.     <groupId>org.springframework.boot</groupId>
  4.     <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <!-- MyBatis Spring Boot Starter -->
  7. <dependency>
  8.     <groupId>org.mybatis.spring.boot</groupId>
  9.     <artifactId>mybatis-spring-boot-starter</artifactId>
  10.     <version>3.0.2</version>
  11. </dependency>
  12. <!-- Druid Spring Boot Starter -->
  13. <dependency>
  14.     <groupId>com.alibaba</groupId>
  15.     <artifactId>druid-spring-boot-3-starter</artifactId>
  16.     <version>1.2.20</version>
  17. </dependency>
  18. <!-- MySQL Connector -->
  19. <dependency>
  20.     <groupId>com.mysql</groupId>
  21.     <artifactId>mysql-connector-j</artifactId>
  22.     <scope>runtime</scope>
  23. </dependency>
复制代码
注意:Druid在Spring Boot 3下需使用druid-spring-boot-3-starter,否则可能不兼容。

2. 配置数据源和MyBatis
在application.yml中配置Druid数据源以及MyBatis映射路径:
  1. spring:
  2.   datasource:
  3.     url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
  4.     username: root
  5.     password: your_password
  6.     driver-class-name: com.mysql.cj.jdbc.Driver
  7.     type: com.alibaba.druid.pool.DruidDataSource
  8.     druid:
  9.       initial-size: 5
  10.       min-idle: 5
  11.       max-active: 20
  12.       max-wait: 60000
  13.       stat-view-servlet:
  14.         enabled: true
  15.         url-pattern: /druid/*
  16. mybatis:
  17.   mapper-locations: classpath:mapper/*.xml
  18.   type-aliases-package: com.example.entity
  19.   configuration:
  20.     map-underscore-to-camel-case: true
复制代码
这里开启了下划线到驼峰的自动映射,便于实体类属性与数据库字段对应。

3. 数据库表结构
原文提供了accounting表,采用InnoDB引擎、utf8_general_ci字符集。建表语句如下:
  1. -- 会计记账表
  2. DROP TABLE IF EXISTS `accounting`;
  3. CREATE TABLE `accounting` (
  4.   `acc_ID` varchar(50) NOT NULL COMMENT 'ID',
  5.   `acc_Category` varchar(50) COMMENT '类型(餐饮、交通等)',
  6.   `acc_Item` varchar(50) DEFAULT NULL COMMENT '支付行为',
  7.   `acc_Name` varchar(50) DEFAULT NULL COMMENT '名称',
  8.   `acc_Amount` decimal(8,2) COMMENT '金额',
  9.   `acc_Type` bit COMMENT '账单类型(1收入/0支出)',
  10.   `acc_ByTime` date COMMENT '发生日期',
  11.   `acc_Notes` varchar(2000) DEFAULT NULL COMMENT '备注',
  12.   `acc_Count` double DEFAULT NULL COMMENT '数量',
  13.   `acc_AtTime` datetime COMMENT '操作日期',
  14.   PRIMARY KEY (`acc_ID`) USING BTREE
  15. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci COMMENT='会计记账';
复制代码
注意:原表主键字段为`accID`,建表语句中写的`acc_ID`,实际以SQL为准。

4. 实体类
创建对应实体,字段使用下划线转驼峰命名:
  1. package com.example.entity;
  2. import java.math.BigDecimal;
  3. import java.time.LocalDate;
  4. import java.time.LocalDateTime;
  5. public class Accounting {
  6.     private String accId;
  7.     private String accCategory;
  8.     private String accItem;
  9.     private String accName;
  10.     private BigDecimal accAmount;
  11.     private Boolean accType;  // true收入,false支出
  12.     private LocalDate accByTime;
  13.     private String accNotes;
  14.     private Double accCount;
  15.     private LocalDateTime accAtTime;
  16.     // getter/setter省略(可用lombok @Data简化)
  17. }
复制代码

5. Mapper接口和XML
新建Mapper接口:
  1. package com.example.mapper;
  2. import com.example.entity.Accounting;
  3. import org.apache.ibatis.annotations.Mapper;
  4. import java.util.List;
  5. @Mapper
  6. public interface AccountingMapper {
  7.     List<Accounting> findAll();
  8.     Accounting findById(String id);
  9.     int insert(Accounting accounting);
  10.     int update(Accounting accounting);
  11.     int deleteById(String id);
  12. }
复制代码
在resources/mapper/下创建AccountingMapper.xml:
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3.         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.example.mapper.AccountingMapper">
  5.     <resultMap id="BaseResultMap" type="Accounting">
  6.         <id column="acc_ID" property="accId" />
  7.         <result column="acc_Category" property="accCategory" />
  8.         <result column="acc_Item" property="accItem" />
  9.         <result column="acc_Name" property="accName" />
  10.         <result column="acc_Amount" property="accAmount" />
  11.         <result column="acc_Type" property="accType" />
  12.         <result column="acc_ByTime" property="accByTime" />
  13.         <result column="acc_Notes" property="accNotes" />
  14.         <result column="acc_Count" property="accCount" />
  15.         <result column="acc_AtTime" property="accAtTime" />
  16.     </resultMap>
  17.     <select id="findAll" resultMap="BaseResultMap">
  18.         SELECT * FROM accounting
  19.     </select>
  20.     <select id="findById" resultMap="BaseResultMap" parameterType="String">
  21.         SELECT * FROM accounting WHERE acc_ID = #{id}
  22.     </select>
  23.     <insert id="insert" parameterType="Accounting">
  24.         INSERT INTO accounting (acc_ID, acc_Category, acc_Item, acc_Name, acc_Amount, acc_Type, acc_ByTime, acc_Notes, acc_Count, acc_AtTime)
  25.         VALUES (#{accId}, #{accCategory}, #{accItem}, #{accName}, #{accAmount}, #{accType}, #{accByTime}, #{accNotes}, #{accCount}, #{accAtTime})
  26.     </insert>
  27.     <update id="update" parameterType="Accounting">
  28.         UPDATE accounting
  29.         SET acc_Category = #{accCategory},
  30.             acc_Item = #{accItem},
  31.             acc_Name = #{accName},
  32.             acc_Amount = #{accAmount},
  33.             acc_Type = #{accType},
  34.             acc_ByTime = #{accByTime},
  35.             acc_Notes = #{accNotes},
  36.             acc_Count = #{accCount},
  37.             acc_AtTime = #{accAtTime}
  38.         WHERE acc_ID = #{accId}
  39.     </update>
  40.     <delete id="deleteById" parameterType="String">
  41.         DELETE FROM accounting WHERE acc_ID = #{id}
  42.     </delete>
  43. </mapper>
复制代码

6. Service层和Controller
Service接口:
  1. public interface AccountingService {
  2.     List<Accounting> findAll();
  3.     Accounting findById(String id);
  4.     void save(Accounting accounting);
  5.     void update(Accounting accounting);
  6.     void delete(String id);
  7. }
复制代码
实现类(使用@Transactional):
  1. @Service
  2. @Transactional
  3. public class AccountingServiceImpl implements AccountingService {
  4.     @Autowired
  5.     private AccountingMapper mapper;
  6.     @Override
  7.     public List<Accounting> findAll() {
  8.         return mapper.findAll();
  9.     }
  10.     @Override
  11.     public Accounting findById(String id) {
  12.         return mapper.findById(id);
  13.     }
  14.     @Override
  15.     public void save(Accounting accounting) {
  16.         mapper.insert(accounting);
  17.     }
  18.     @Override
  19.     public void update(Accounting accounting) {
  20.         mapper.update(accounting);
  21.     }
  22.     @Override
  23.     public void delete(String id) {
  24.         mapper.deleteById(id);
  25.     }
  26. }
复制代码
Controller层提供REST接口:
  1. @RestController
  2. @RequestMapping("/accounting")
  3. public class AccountingController {
  4.     @Autowired
  5.     private AccountingService service;
  6.     @GetMapping
  7.     public List<Accounting> list() {
  8.         return service.findAll();
  9.     }
  10.     @GetMapping("/{id}")
  11.     public Accounting get(@PathVariable String id) {
  12.         return service.findById(id);
  13.     }
  14.     @PostMapping
  15.     public String add(@RequestBody Accounting accounting) {
  16.         service.save(accounting);
  17.         return "success";
  18.     }
  19.     @PutMapping
  20.     public String update(@RequestBody Accounting accounting) {
  21.         service.update(accounting);
  22.         return "success";
  23.     }
  24.     @DeleteMapping("/{id}")
  25.     public String delete(@PathVariable String id) {
  26.         service.delete(id);
  27.         return "success";
  28.     }
  29. }
复制代码

7. 测试验证
启动Spring Boot应用后,可用Postman或curl测试。例如插入一条原文示例数据:
  1. curl -X POST http://localhost:8080/accounting \
  2. -H "Content-Type: application/json" \
  3. -d '{
  4.   "accId":"1",
  5.   "accCategory":"交通",
  6.   "accItem":"现金",
  7.   "accName":"测试",
  8.   "accAmount":88.56,
  9.   "accType":true,
  10.   "accByTime":"2025-01-23",
  11.   "accAtTime":"2025-01-23T10:00:00"
  12. }'
复制代码
也可在数据库直接执行原文提供的Insert语句完成数据初始化。

8. 总结
本文基于Spring Boot 3,整合MyBatis和Druid数据源,实现了对会计记账表的完整CRUD操作。关键点包括:使用druid-spring-boot-3-starter兼容Spring Boot 3;MyBatis Mapper XML中字段映射时注意下划线与驼峰转换;Druid监控页面可通过/druid/index.html查看连接池状态。此示例代码可作为后续开发财务相关模块的基础脚手架。
回复

使用道具 举报

发表于 5 天前 | 显示全部楼层

Re: Spring Boot 3整合MyBatis和Druid实现会计记账表CRUD实例

感谢楼主分享这么详细的Spring Boot 3整合教程!从依赖配置到数据源、建表语句都写得很清楚,对升级到Spring Boot 3的同学很有参考价值。 提一个小细节:实体类最后一行 `private Boo` 应该是 `private Boolean accType;` 吧?另外建表语句中主键字段是 `acc_ID`,但实体类按驼峰命名会是 `accId`,如果开启了 `map-underscore-to-camel-case: true` 应该可以自动映射,不过最好确认一下字段名与SQL定义一致。 期待楼主后续补充完整的CRUD代码实现,尤其是MyBatis的Mapper和Service层写法,这对初学者会很有帮助。再次感谢分享!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

指导单位

江苏省公安厅

江苏省通信管理局

浙江省台州刑侦支队

DEFCON GROUP 86025

Hacking Group 021A

旗下站点

态势感知中心

应急响应中心

红盟安全

联系我们

官方QQ群:112851260

官方邮箱:security#ihonker.org(#改成@)

官方核心成员

关注微信公众号

Archiver|手机版|小黑屋| ( 沪ICP备2021026908号 )

GMT+8, 2026-6-14 05:30 , Processed in 0.029439 second(s), 17 queries , Gzip On, Redis On.

Powered by ihonker.com

Copyright © 2015-现在.

  • 返回顶部