随着Spring Boot 3的发布,许多开发者开始将项目升级至此版本。本文通过一个会计记账表(accounting)的增删改查示例,演示如何在Spring Boot 3中整合MyBatis和Druid数据源。
环境要求:JDK 17+、Spring Boot 3.x。
1. 添加项目依赖
在pom.xml中引入核心依赖:- <!-- Spring Boot Starter Web -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <!-- MyBatis Spring Boot Starter -->
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>3.0.2</version>
- </dependency>
- <!-- Druid Spring Boot Starter -->
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid-spring-boot-3-starter</artifactId>
- <version>1.2.20</version>
- </dependency>
- <!-- MySQL Connector -->
- <dependency>
- <groupId>com.mysql</groupId>
- <artifactId>mysql-connector-j</artifactId>
- <scope>runtime</scope>
- </dependency>
复制代码 注意:Druid在Spring Boot 3下需使用druid-spring-boot-3-starter,否则可能不兼容。
2. 配置数据源和MyBatis
在application.yml中配置Druid数据源以及MyBatis映射路径:- spring:
- datasource:
- url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
- username: root
- password: your_password
- driver-class-name: com.mysql.cj.jdbc.Driver
- type: com.alibaba.druid.pool.DruidDataSource
- druid:
- initial-size: 5
- min-idle: 5
- max-active: 20
- max-wait: 60000
- stat-view-servlet:
- enabled: true
- url-pattern: /druid/*
- mybatis:
- mapper-locations: classpath:mapper/*.xml
- type-aliases-package: com.example.entity
- configuration:
- map-underscore-to-camel-case: true
复制代码 这里开启了下划线到驼峰的自动映射,便于实体类属性与数据库字段对应。
3. 数据库表结构
原文提供了accounting表,采用InnoDB引擎、utf8_general_ci字符集。建表语句如下:- -- 会计记账表
- DROP TABLE IF EXISTS `accounting`;
- CREATE TABLE `accounting` (
- `acc_ID` varchar(50) NOT NULL COMMENT 'ID',
- `acc_Category` varchar(50) COMMENT '类型(餐饮、交通等)',
- `acc_Item` varchar(50) DEFAULT NULL COMMENT '支付行为',
- `acc_Name` varchar(50) DEFAULT NULL COMMENT '名称',
- `acc_Amount` decimal(8,2) COMMENT '金额',
- `acc_Type` bit COMMENT '账单类型(1收入/0支出)',
- `acc_ByTime` date COMMENT '发生日期',
- `acc_Notes` varchar(2000) DEFAULT NULL COMMENT '备注',
- `acc_Count` double DEFAULT NULL COMMENT '数量',
- `acc_AtTime` datetime COMMENT '操作日期',
- PRIMARY KEY (`acc_ID`) USING BTREE
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci COMMENT='会计记账';
复制代码 注意:原表主键字段为`accID`,建表语句中写的`acc_ID`,实际以SQL为准。
4. 实体类
创建对应实体,字段使用下划线转驼峰命名:- package com.example.entity;
- import java.math.BigDecimal;
- import java.time.LocalDate;
- import java.time.LocalDateTime;
- public class Accounting {
- private String accId;
- private String accCategory;
- private String accItem;
- private String accName;
- private BigDecimal accAmount;
- private Boolean accType; // true收入,false支出
- private LocalDate accByTime;
- private String accNotes;
- private Double accCount;
- private LocalDateTime accAtTime;
- // getter/setter省略(可用lombok @Data简化)
- }
复制代码
5. Mapper接口和XML
新建Mapper接口:- package com.example.mapper;
- import com.example.entity.Accounting;
- import org.apache.ibatis.annotations.Mapper;
- import java.util.List;
- @Mapper
- public interface AccountingMapper {
- List<Accounting> findAll();
- Accounting findById(String id);
- int insert(Accounting accounting);
- int update(Accounting accounting);
- int deleteById(String id);
- }
复制代码 在resources/mapper/下创建AccountingMapper.xml:- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.example.mapper.AccountingMapper">
- <resultMap id="BaseResultMap" type="Accounting">
- <id column="acc_ID" property="accId" />
- <result column="acc_Category" property="accCategory" />
- <result column="acc_Item" property="accItem" />
- <result column="acc_Name" property="accName" />
- <result column="acc_Amount" property="accAmount" />
- <result column="acc_Type" property="accType" />
- <result column="acc_ByTime" property="accByTime" />
- <result column="acc_Notes" property="accNotes" />
- <result column="acc_Count" property="accCount" />
- <result column="acc_AtTime" property="accAtTime" />
- </resultMap>
- <select id="findAll" resultMap="BaseResultMap">
- SELECT * FROM accounting
- </select>
- <select id="findById" resultMap="BaseResultMap" parameterType="String">
- SELECT * FROM accounting WHERE acc_ID = #{id}
- </select>
- <insert id="insert" parameterType="Accounting">
- INSERT INTO accounting (acc_ID, acc_Category, acc_Item, acc_Name, acc_Amount, acc_Type, acc_ByTime, acc_Notes, acc_Count, acc_AtTime)
- VALUES (#{accId}, #{accCategory}, #{accItem}, #{accName}, #{accAmount}, #{accType}, #{accByTime}, #{accNotes}, #{accCount}, #{accAtTime})
- </insert>
- <update id="update" parameterType="Accounting">
- UPDATE accounting
- SET acc_Category = #{accCategory},
- acc_Item = #{accItem},
- acc_Name = #{accName},
- acc_Amount = #{accAmount},
- acc_Type = #{accType},
- acc_ByTime = #{accByTime},
- acc_Notes = #{accNotes},
- acc_Count = #{accCount},
- acc_AtTime = #{accAtTime}
- WHERE acc_ID = #{accId}
- </update>
- <delete id="deleteById" parameterType="String">
- DELETE FROM accounting WHERE acc_ID = #{id}
- </delete>
- </mapper>
复制代码
6. Service层和Controller
Service接口:- public interface AccountingService {
- List<Accounting> findAll();
- Accounting findById(String id);
- void save(Accounting accounting);
- void update(Accounting accounting);
- void delete(String id);
- }
复制代码 实现类(使用@Transactional):- @Service
- @Transactional
- public class AccountingServiceImpl implements AccountingService {
- @Autowired
- private AccountingMapper mapper;
- @Override
- public List<Accounting> findAll() {
- return mapper.findAll();
- }
- @Override
- public Accounting findById(String id) {
- return mapper.findById(id);
- }
- @Override
- public void save(Accounting accounting) {
- mapper.insert(accounting);
- }
- @Override
- public void update(Accounting accounting) {
- mapper.update(accounting);
- }
- @Override
- public void delete(String id) {
- mapper.deleteById(id);
- }
- }
复制代码 Controller层提供REST接口:- @RestController
- @RequestMapping("/accounting")
- public class AccountingController {
- @Autowired
- private AccountingService service;
- @GetMapping
- public List<Accounting> list() {
- return service.findAll();
- }
- @GetMapping("/{id}")
- public Accounting get(@PathVariable String id) {
- return service.findById(id);
- }
- @PostMapping
- public String add(@RequestBody Accounting accounting) {
- service.save(accounting);
- return "success";
- }
- @PutMapping
- public String update(@RequestBody Accounting accounting) {
- service.update(accounting);
- return "success";
- }
- @DeleteMapping("/{id}")
- public String delete(@PathVariable String id) {
- service.delete(id);
- return "success";
- }
- }
复制代码
7. 测试验证
启动Spring Boot应用后,可用Postman或curl测试。例如插入一条原文示例数据:- curl -X POST http://localhost:8080/accounting \
- -H "Content-Type: application/json" \
- -d '{
- "accId":"1",
- "accCategory":"交通",
- "accItem":"现金",
- "accName":"测试",
- "accAmount":88.56,
- "accType":true,
- "accByTime":"2025-01-23",
- "accAtTime":"2025-01-23T10:00:00"
- }'
复制代码 也可在数据库直接执行原文提供的Insert语句完成数据初始化。
8. 总结
本文基于Spring Boot 3,整合MyBatis和Druid数据源,实现了对会计记账表的完整CRUD操作。关键点包括:使用druid-spring-boot-3-starter兼容Spring Boot 3;MyBatis Mapper XML中字段映射时注意下划线与驼峰转换;Druid监控页面可通过/druid/index.html查看连接池状态。此示例代码可作为后续开发财务相关模块的基础脚手架。 |