欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 焦点 > IntelliJ IDEA中Spring Boot项目整合MyBatis:从零实现高效数据持久化

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

2025/4/18 12:50:11 来源:https://blog.csdn.net/weixin_42593797/article/details/146839977  浏览:    关键词: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依赖

确保包含以下核心依赖:

<!-- 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)

spring:datasource:url: jdbc:mysql://localhost:3306/mybatis_demo?useSSL=false&serverTimezone=UTCusername: rootpassword: 123456driver-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注解:

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

‌四、两种开发模式实战

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

1. ‌定义实体类
@Data
public class User {private Long id;private String username;private String email;private LocalDateTime createTime;
}
2. ‌编写Mapper接口
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)
<?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接口中声明方法
public interface UserMapper {List<User> selectAll();
}

五、Service与Controller层

‌1. 业务逻辑层(Service)

@Service
public class UserService {@Autowiredprivate UserMapper userMapper;public User getUserById(Long id) {return userMapper.selectById(id);}public List<User> getAllUsers() {return userMapper.selectAll();}
}

‌2. REST接口层(Controller)

@RestController
@RequestMapping("/api/users")
public class UserController {@Autowiredprivate UserService userService;@GetMapping("/{id}")public User getUser(@PathVariable Long id) {return userService.getUserById(id);}@GetMappingpublic List<User> getAllUsers() {return userService.getAllUsers();}
}

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

‌1. 分页查询实现

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,返回分页数据:

{"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中添加资源过滤:
      <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,兼顾开发效率与维护性。本文从基础配置到高级应用,覆盖了企业级开发的核心需求。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词