如何在Spring Boot项目中配置MyBatis?
时间: 2025-01-07 22:14:25 浏览: 4
在Spring Boot项目中配置MyBatis可以通过以下几个步骤实现:
1. **添加依赖**:
首先,在你的`pom.xml`文件中添加MyBatis和数据库驱动相关的依赖。例如,如果你使用的是MySQL数据库,可以添加以下依赖:
```xml
<dependencies>
<!-- MyBatis Spring Boot Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- MySQL Connector/J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
```
2. **配置数据源**:
在`application.properties`或`application.yml`文件中配置数据库连接信息。例如,使用`application.properties`:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/your_database
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# MyBatis 配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.yourapp.entity
```
3. **创建实体类**:
在`com.example.yourapp.entity`包下创建与数据库表对应的实体类。例如:
```java
package com.example.yourapp.entity;
public class User {
private Long id;
private String name;
private String email;
// Getters and Setters
}
```
4. **创建Mapper接口**:
在`com.example.yourapp.mapper`包下创建Mapper接口。例如:
```java
package com.example.yourapp.mapper;
import com.example.yourapp.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users")
List<User> findAll();
}
```
5. **创建Mapper XML文件(可选)**:
如果你更喜欢使用XML文件来编写SQL语句,可以在`src/main/resources/mapper`目录下创建XML文件。例如,`UserMapper.xml`:
```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.yourapp.mapper.UserMapper">
<select id="findAll" resultType="com.example.yourapp.entity.User">
SELECT * FROM users
</select>
</mapper>
```
6. **使用Mapper**:
在你的服务类或控制器中使用Mapper接口。例如:
```java
package com.example.yourapp.service;
import com.example.yourapp.entity.User;
import com.example.yourapp.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> getAllUsers() {
return userMapper.findAll();
}
}
```
通过以上步骤,你就可以在Spring Boot项目中成功配置并使用MyBatis了。
阅读全文