# 实现Spring Boot + MyBatis + Thymeleaf

## 概述
在这篇文章中,我将向你介绍如何使用Spring Boot框架集成MyBatis持久层框架和Thymeleaf模板引擎。Spring Boot是一个快速开发Java应用程序的框架,MyBatis是一个优秀的持久层框架,Thymeleaf是一款优秀的Java模板引擎。通过整合这三者,我们可以快速开发出一个功能完善的Java Web应用程序。

## 整体流程
以下是整合Spring Boot + MyBatis + Thymeleaf的流程:

| 步骤 | 描述 |
| ----- | -------- |
| 1 | 创建Spring Boot项目 |
| 2 | 配置MyBatis |
| 3 | 配置Thymeleaf |
| 4 | 创建实体类 |
| 5 | 创建Mapper接口 |
| 6 | 编写Mapper.xml |
| 7 | 创建Service层 |
| 8 | 创建Controller层 |
| 9 | 创建Thymeleaf模板 |
| 10 | 运行项目 |

## 每一步具体操作
### 步骤1:创建Spring Boot项目
首先,我们需要创建一个Spring Boot项目。可以使用Spring Initializr来快速生成一个基本的Spring Boot项目,包括项目结构、依赖等。
```java
// 代码示例
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```

### 步骤2:配置MyBatis
在Spring Boot项目中集成MyBatis需要在`application.properties`文件中配置数据库连接信息、MyBatis相关配置。
```java
// 添加MyBatis依赖

org.mybatis.spring.boot
mybatis-spring-boot-starter


// application.properties配置示例
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapper-locations=classpath*:mapper/*.xml
```

### 步骤3:配置Thymeleaf
配置Thymeleaf模板引擎需要在`application.properties`文件中配置Thymeleaf相关属性。
```java
// 添加Thymeleaf依赖

org.springframework.boot
spring-boot-starter-thymeleaf


// application.properties配置示例
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
```

### 步骤4:创建实体类
创建一个实体类,用于映射数据库表的字段。
```java
// 代码示例
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
// 省略getter和setter方法
}
```

### 步骤5:创建Mapper接口
创建一个Mapper接口,用于定义数据库操作的方法。
```java
// 代码示例
@Mapper
public interface UserMapper {
User findById(Long id);
List findAll();
void save(User user);
void update(User user);
void delete(Long id);
}
```

### 步骤6:编写Mapper.xml
在resources文件夹下创建mapper文件夹,编写Mapper.xml文件,定义SQL语句。
```xml





```

### 步骤7:创建Service层
创建一个Service层,用于处理业务逻辑。
```java
// 代码示例
@Service
public class UserService {
@Autowired
private UserMapper userMapper;

public User findById(Long id) {
return userMapper.findById(id);
}
// 省略其他方法
}
```

### 步骤8:创建Controller层
创建一个Controller层,用于接收HTTP请求并调用Service层处理。
```java
// 代码示例
@RestController
public class UserController {
@Autowired
private UserService userService;

@GetMapping("/user/{id}")
public User getUserById(@PathVariable Long id) {
return userService.findById(id);
}
// 省略其他方法
}
```

### 步骤9:创建Thymeleaf模板
在`src/main/resources/templates`目录下创建Thymeleaf模板文件,用于前端页面展示。
```html




User Details





```

### 步骤10:运行项目
使用IDE启动Spring Boot项目,访问前端页面测试功能。

通过以上步骤,你已经成功实现了Spring Boot + MyBatis + Thymeleaf的集成。希望对你有帮助!