IntelliJ IDEA中Spring Boot项目整合MyBatis:从零实现高效数据持久化

‌前言

MyBatis作为一款灵活且强大的‌ORM框架‌ ,凭借其直观的SQL映射和动态SQL能力,成为Java开发者首选的持久层解决方案。本文将以‌Spring Boot 3.4.x‌ 和‌MyBatis 3.5.x‌ 为例,手把手教你‌在IDEA中集成MyBatis‌ ,涵盖‌注解与XML两种开发模式‌、‌分页插件集成‌、‌多数据源配置‌ 及‌生产级避坑指南‌,助你轻松实现高效数据操作!


‌一、环境准备

1. ‌基础环境

  • JDK 17+(推荐OpenJDK 17/21)
  • IntelliJ IDEA 2023.1+
  • MySQL 8.x(或其他支持JDBC的数据库)

2. ‌项目初始化

  • 通过Spring Initializr创建项目,选择:
    • Spring Boot 3.4.x
    • 依赖项:Spring Web, MySQL Driver, ‌MyBatis Framework‌
    • (可选)Lombok简化代码

‌二、添加MyBatis依赖

‌1. 验证pom.xml依赖

确保包含以下核心依赖:

bash 复制代码
<!-- MyBatis官方Starter(适配Spring Boot 3.4.x) -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>3.0.3</version>
</dependency>

<!-- MySQL驱动 -->
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
</dependency>

<!-- 分页插件(可选) -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>2.1.0</version>
</dependency>

‌注‌:Spring Boot 3.4.x需使用MyBatis Starter 3.0.x+,兼容Jakarta EE 9+规范。


‌三、配置数据源与MyBatis

‌1. 数据库连接配置(application.yml)

bash 复制代码
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis_demo?useSSL=false&serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

# MyBatis配置
mybatis:
  mapper-locations: classpath:mapper/*.xml  # XML映射文件路径
  type-aliases-package: com.example.demo.entity  # 实体类别名包
  configuration:
    map-underscore-to-camel-case: true  # 开启驼峰命名转换
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  # 输出SQL日志

‌2. 配置Mapper扫描(可选)

在启动类添加@MapperScan注解:

bash 复制代码
@SpringBootApplication
@MapperScan("com.example.demo.mapper")  // 指定Mapper接口包路径
public class DemoApplication { ... }

‌四、两种开发模式实战

‌模式1:注解开发(适合简单SQL)

1. ‌定义实体类
bash 复制代码
@Data
public class User {
    private Long id;
    private String username;
    private String email;
    private LocalDateTime createTime;
}
2. ‌编写Mapper接口
bash 复制代码
public interface UserMapper {
    // 插入并返回自增ID
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("INSERT INTO user(username, email) VALUES(#{username}, #{email})")
    int insertUser(User user);

    @Select("SELECT * FROM user WHERE id = #{id}")
    User selectById(Long id);
}

‌模式2:XML开发(适合复杂SQL)

1. ‌创建XML映射文件(resources/mapper/UserMapper.xml)
bash 复制代码
<?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.demo.mapper.UserMapper">
    <resultMap id="userMap" type="User">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="email" property="email"/>
        <result column="create_time" property="createTime"/>
    </resultMap>

    <select id="selectAll" resultMap="userMap">
        SELECT * FROM user
    </select>
</mapper>
2. ‌在Mapper接口中声明方法
bash 复制代码
public interface UserMapper {
    List<User> selectAll();
}

五、Service与Controller层

‌1. 业务逻辑层(Service)

bash 复制代码
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    public List<User> getAllUsers() {
        return userMapper.selectAll();
    }
}

‌2. REST接口层(Controller)

bash 复制代码
@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
}

‌六、高级功能:分页插件

‌1. 分页查询实现

bash 复制代码
public PageInfo<User> getUsersByPage(int pageNum, int pageSize) {
    PageHelper.startPage(pageNum, pageSize);
    List<User> users = userMapper.selectAll();
    return new PageInfo<>(users);
}

‌2. 接口测试

请求GET /api/users/page?pageNum=1&pageSize=5,返回分页数据:

bash 复制代码
{
  "total": 20,
  "list": [ ... ],
  "pageNum": 1,
  "pageSize": 5
}

‌七、常见问题与解决方案

Q1:Mapper接口无法注入(NoSuchBeanDefinitionException)

  • 原因‌:未扫描到Mapper接口。
  • 解决‌
    • 检查@MapperScan路径是否正确。
    • 确认Mapper接口添加了@Mapper注解(若未用@MapperScan)。

‌Q2:XML文件未找到(Invalid bound statement)

  • 解决‌
    • 检查mybatis.mapper-locations路径是否匹配。

    • pom.xml中添加资源过滤:

      bash 复制代码
      <build>
          <resources>
              <resource>
                  <directory>src/main/resources</directory>
                  <includes>
                      <include>**/*.xml</include>
                  </includes>
              </resource>
          </resources>
      </build>

‌Q3:事务管理失效

  • 解决‌
    • 在Service方法添加@Transactional注解。
    • 确认已启用事务管理(Spring Boot默认启用)。

总结

通过Spring Boot与MyBatis的整合,开发者可以灵活选择注解或XML方式管理SQL,兼顾开发效率与维护性。本文从基础配置到高级应用,覆盖了企业级开发的核心需求。

相关推荐
考虑考虑1 小时前
Jpa使用union all
java·spring boot·后端
用户3721574261351 小时前
Java 实现 Excel 与 TXT 文本高效互转
java
浮游本尊2 小时前
Java学习第22天 - 云原生与容器化
java
渣哥4 小时前
原来 Java 里线程安全集合有这么多种
java
间彧4 小时前
Spring Boot集成Spring Security完整指南
java
间彧5 小时前
Spring Secutiy基本原理及工作流程
java
Java水解6 小时前
JAVA经典面试题附答案(持续更新版)
java·后端·面试
洛小豆8 小时前
在Java中,Integer.parseInt和Integer.valueOf有什么区别
java·后端·面试
前端小张同学8 小时前
服务器上如何搭建jenkins 服务CI/CD😎😎
java·后端
ytadpole8 小时前
Spring Cloud Gateway:一次不规范 URL 引发的路由转发404问题排查
java·后端