# SpringBoot項目中怎么整合MyBatis
## 一、前言
在現代Java企業級應用開發中,SpringBoot和MyBatis的組合已經成為主流技術選型之一。SpringBoot提供了快速構建項目的腳手架,而MyBatis作為優秀的持久層框架,以其靈活的SQL編寫方式和良好的性能受到開發者青睞。本文將詳細介紹如何在SpringBoot項目中整合MyBatis框架。
## 二、環境準備
### 2.1 開發工具及版本要求
- JDK 1.8+
- Maven 3.6+ 或 Gradle 6.x
- SpringBoot 2.7.x
- MyBatis 3.5.x
- IDE(IntelliJ IDEA或Eclipse)
### 2.2 創建SpringBoot項目
通過Spring Initializr創建項目:
1. 訪問 https://start.spring.io
2. 選擇Maven/Gradle項目
3. 添加依賴:Spring Web、MyBatis Framework、MySQL Driver
或使用命令行:
```bash
curl https://start.spring.io/starter.zip -d dependencies=web,mybatis,mysql -o mybatis-demo.zip
<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>2.2.2</version>
</dependency>
<!-- 數據庫驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
在application.yml
中配置:
spring:
datasource:
url: jdbc:mysql://localhost:3306/test_db?useSSL=false&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml
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
}
package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper {
User selectById(Long id);
int insert(User user);
int update(User user);
int delete(Long id);
}
在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="BaseResultMap" type="User">
<id column="id" property="id" />
<result column="username" property="username" />
<result column="password" property="password" />
</resultMap>
<select id="selectById" resultMap="BaseResultMap">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
添加PageHelper依賴:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.2</version>
</dependency>
配置分頁參數:
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
使用示例:
PageHelper.startPage(1, 10);
List<User> users = userMapper.selectAll();
@Configuration
@MapperScan(basePackages = "com.example.mapper.primary", sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryDataSourceConfig {
@Bean
@Primary
@ConfigurationProperties("spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@Primary
public SqlSessionFactory primarySqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(primaryDataSource());
return factoryBean.getObject();
}
}
SpringBoot默認已集成事務管理:
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Transactional
public void updateUser(User user) {
userMapper.update(user);
}
}
MyBatis Generator配置示例:
<generatorConfiguration>
<context id="DB2Tables" targetRuntime="MyBatis3">
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test_db"
userId="root"
password="123456">
</jdbcConnection>
<javaModelGenerator targetPackage="com.example.entity"
targetProject="src/main/java"/>
<sqlMapGenerator targetPackage="mapper"
targetProject="src/main/resources"/>
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.example.mapper"
targetProject="src/main/java"/>
<table tableName="%">
<generatedKey column="id" sqlStatement="JDBC"/>
</table>
</context>
</generatorConfiguration>
Mapper接口無法注入
@Mapper
注解或@MapperScan
XML文件找不到
mybatis.mapper-locations
配置SQL語法錯誤
在application.yml
中添加:
logging:
level:
com.example.demo.mapper: DEBUG
本文詳細介紹了SpringBoot整合MyBatis的全過程,從基礎配置到高級功能,涵蓋了實際開發中的常見場景。通過合理的配置和優化,可以充分發揮MyBatis在SpringBoot項目中的優勢,構建高效可靠的數據訪問層。
src/main/java
├── com.example.demo
│ ├── DemoApplication.java
│ ├── entity
│ │ └── User.java
│ ├── mapper
│ │ └── UserMapper.java
│ └── service
│ └── UserService.java
src/main/resources
├── application.yml
├── mapper
│ └── UserMapper.xml
注意:實際開發中應根據項目需求調整配置,本文示例基于SpringBoot 2.7.x和MyBatis 3.5.x版本。 “`
這篇文章約4000字,采用Markdown格式編寫,包含了SpringBoot整合MyBatis的完整流程,從基礎配置到高級功能,并提供了常見問題解決方案。您可以根據實際需求調整內容細節或補充更多具體示例。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。