一,SpringBoot 与 MyBatis 介绍
SpringBoot 是 Spring 框架的扩展,它简化了 Spring 应用的初始搭建和开发过程,通过自动配置和起步依赖,让开发者可以更专注于业务逻辑。
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射,避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程。
MyBatis 核心优势在于平衡了 SQL 的灵活性与 ORM 的便捷性。与全自动 ORM 框架相比,MyBatis 允许开发者直接编写原生 SQL,支持复杂查询、存储过程和数据库特定优化,避免了过度封装带来的性能损耗。通过 XML 或注解实现结果集映射,它能处理复杂对象关系,同时保持对查询逻辑的精确控制。
二,集成步骤
- 添加依赖
在pom.xml中添加 SpringBoot 和 MyBatis 的依赖:
<dependencies>
<!-- SpringBoot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.2</version>
</dependency>
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 其他依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- 配置数据源
在application.properties中配置数据库连接信息:
# 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/yourdbname?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# MyBatis配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.demo.entity
- 创建实体类
package com.example.demo.entity;
public class User {
private Long id;
private String username;
private String password;
// getters and setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}
- 创建 Mapper 接口
package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
List<User> findAll();
User findById(Long id);
int insert(User user);
int update(User user);
int delete(Long id);
}
- 创建 Mapper 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">
<select id="findAll" resultType="User">
SELECT * FROM user
</select>
<select id="findById" parameterType="Long" resultType="User">
SELECT * FROM user WHERE id = #{id}
</select>
<insert id="insert" parameterType="User">
INSERT INTO user(username, password)
VALUES (#{username}, #{password})
</insert>
<update id="update" parameterType="User">
UPDATE user
SET username = #{username},
password = #{password}
WHERE id = #{id}
</update>
<delete id="delete" parameterType="Long">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
- 创建 Service 和 Controller
// Service层
package com.example.demo.service;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> findAll() {
return userMapper.findAll();
}
public User findById(Long id) {
return userMapper.findById(id);
}
public int insert(User user) {
return userMapper.insert(user);
}
public int update(User user) {
return userMapper.update(user);
}
public int delete(Long id) {
return userMapper.delete(id);
}
}
// Controller层
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> findAll() {
return userService.findAll();
}
@GetMapping("/{id}")
public User findById(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping
public int insert(@RequestBody User user) {
return userService.insert(user);
}
@PutMapping
public int update(@RequestBody User user) {
return userService.update(user);
}
@DeleteMapping("/{id}")
public int delete(@PathVariable Long id) {
return userService.delete(id);
}
}
- 主应用类
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
三,注意事项
1. Mapper 接口与 XML 映射
确保 Mapper 接口与 XML 文件中的 namespace 一致方法名和 SQL 语句的 id 保持一致注意参数类型和返回类型的匹配
2. 事务管理
在 Service 层的方法上使用@Transactional注解管理事务确保事务方法在 Service 层而不是 Controller 层
3. SQL 注入问题
使用#{}而不是${}来防止 SQL 注入对于需要动态表名或列名的情况,要手动做好参数校验
4. 分页处理
可以使用 MyBatis 分页插件如 PageHelper 简化分页操作
注意分页插件的配置和使用方式
5. 配置优先级
注意 Java 配置和 XML 配置的优先级,避免冲突推荐使用 Java 配置为主,XML 配置为辅
6. 日志配置
配置 MyBatis 的日志以便调试,可在application.properties中添加:
# properties
logging.level.com.example.demo.mapper=DEBUG
7.性能优化
合理配置缓存,避免过度使用缓存复杂查询使用 ResultMap 进行结果映射批量操作使用标签
8. 注解方式
可以使用@Select、@Insert等注解替代 XML 文件复杂 SQL 建议还是使用 XML 配置
四,利用 idea springboot 集成 mybatis
1. 创建 Spring Boot 项目
请参考 :https://blog.csdn.net/hugejiletuhugejiltu/article/details/148891905?spm=1011.2124.3001.6209
添加以下依赖:
Spring Web
Spring Data JPA
MySQL Driver(或其他数据库驱动)
MyBatis Framework
在这里插入图片描述
2. 配置数据库连接
在application.properties或application.yml中添加数据库配置:
spring.datasource.url=jdbc:mysql://localhost:3306/yourdbname
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# MyBatis配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.demo.entity
3. 创建实体类
创建与数据库表对应的实体类:
package com.example.demo.entity;
public class User {
private Long id;
private String username;
private String password;
// getters and setters
}
4. 创建 Mapper 接口
定义数据库操作方法:
package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
List<User> findAll();
User findById(Long id);
int insert(User user);
int update(User user);
int delete(Long id);
}
5. 创建 Mapper 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">
<select id="findAll" resultType="User">
SELECT * FROM user
</select>
<select id="findById" parameterType="Long" resultType="User">
SELECT * FROM user WHERE id = #{id}
</select>
<insert id="insert" parameterType="User">
INSERT INTO user(username, password)
VALUES (#{username}, #{password})
</insert>
<update id="update" parameterType="User">
UPDATE user
SET username = #{username},
password = #{password}
WHERE id = #{id}
</update>
<delete id="delete" parameterType="Long">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
6. 创建 Service 层
package com.example.demo.service;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> findAll() {
return userMapper.findAll();
}
public User findById(Long id) {
return userMapper.findById(id);
}
public int insert(User user) {
return userMapper.insert(user);
}
public int update(User user) {
return userMapper.update(user);
}
public int delete(Long id) {
return userMapper.delete(id);
}
}
7. 创建 Controller 层
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> findAll() {
return userService.findAll();
}
@GetMapping("/{id}")
public User findById(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping
public int insert(@RequestBody User user) {
return userService.insert(user);
}
@PutMapping
public int update(@RequestBody User user) {
return userService.update(user);
}
@DeleteMapping("/{id}")
public int delete(@PathVariable Long id) {
return userService.delete(id);
}
}
8. 运行项目
启动 Spring Boot 应用,测试 API 接口。你可以使用 Postman 或浏览器访问:
GET http://localhost:8080/users
GET http://localhost:8080/users/1
POST http://localhost:8080/users
PUT http://localhost:8080/users
DELETE http://localhost:8080/users/1
9. 注意事项
确保数据库已创建并正确配置,检查 Mapper 接口和 XML 文件的命名空间匹配
添加@MapperScan注解到主应用类(如果 MyBatis 接口未被自动扫描):
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
五,总结
在 IntelliJ IDEA 中集成 MyBatis 到 Spring Boot 项目,可按以下步骤高效完成:首先通过 Spring Initializr 创建项目,添加 Spring Web、MyBatis Framework、数据库驱动等依赖。接着配置application.properties中的数据库连接信息与 MyBatis 映射文件位置。创建实体类映射数据库表结构,定义 Mapper 接口声明数据库操作方法并添加@Mapper注解。在 resources 目录创建对应 XML 文件实现 SQL 语句,通过 namespace 关联接口。再创建 Service 层调用 Mapper 方法,Controller 层暴露 RESTful 接口。最后运行项目测试接口。注意确保依赖完整、配置无误,必要时添加@MapperScan注解指定扫描路径。