一个简易的,使用mybatis,springboot,Thymeleaf,lombok,springmvc的简短案例吗
时间: 2024-06-11 22:08:48 浏览: 155
好的,下面是一个简单的示例:
1. 创建项目并添加依赖
首先,我们需要创建一个Spring Boot项目,并添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
```
2. 配置数据源和MyBatis
在application.properties文件中添加以下配置:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
```
其中,url、username、password需要根据实际情况进行修改。
3. 创建数据表和实体类
在MySQL中创建一个user表,并创建对应的实体类User:
```sql
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
```
```java
@Data
public class User {
private Long id;
private String name;
private Integer age;
}
```
4. 创建Mapper接口和XML文件
创建UserMapper接口和对应的XML文件:
UserMapper.java:
```java
@Mapper
public interface UserMapper {
List<User> findAll();
}
```
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.demo.mapper.UserMapper">
<select id="findAll" resultType="com.example.demo.entity.User">
select * from user
</select>
</mapper>
```
5. 创建Controller和视图
创建UserController和对应的视图:
```java
@Controller
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/users")
public String findAll(Model model) {
List<User> users = userMapper.findAll();
model.addAttribute("users", users);
return "users";
}
}
```
users.html:
```html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>User List</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>User List</h1>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr th:each="user : ${users}">
<td th:text="${user.id}">ID</td>
<td th:text="${user.name}">Name</td>
<td th:text="${user.age}">Age</td>
</tr>
</table>
</body>
</html>
```
6. 运行项目
启动项目,访问http://localhost:8080/users,即可看到用户列表。
阅读全文