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=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注解:
@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 {
@Autowired
private 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 {
@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. 分页查询实现
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,分身开辟服从与维护性。本文从根本设置到高级应用,覆盖了企业级开辟的核心需求。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]