spring boot + mybatis 简单示例
时间: 2023-08-21 13:05:46 浏览: 110
好的,以下是一个简单的 Spring Boot + Mybatis 示例:
1. 首先,在 pom.xml 中添加以下依赖:
```xml
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.6</version>
</dependency>
<!-- MySQL 连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
</dependencies>
```
2. 在 application.yml 中配置数据库连接信息:
```yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: root
```
3. 创建一个 User 实体类:
```java
public class User {
private Long id;
private String name;
private Integer age;
// getter 和 setter
}
```
4. 创建一个 UserMapper 接口:
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(Long id);
@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
void save(User user);
@Update("UPDATE user SET name=#{name}, age=#{age} WHERE id =#{id}")
void update(User user);
@Delete("DELETE FROM user WHERE id =#{id}")
void delete(Long id);
}
```
5. 创建一个 UserService 类,实现业务逻辑:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User findById(Long id) {
return userMapper.findById(id);
}
public void save(User user) {
userMapper.save(user);
}
public void update(User user) {
userMapper.update(user);
}
public void delete(Long id) {
userMapper.delete(id);
}
}
```
6. 创建一个 UserController 类,处理 HTTP 请求:
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User findById(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping
public void save(@RequestBody User user) {
userService.save(user);
}
@PutMapping
public void update(@RequestBody User user) {
userService.update(user);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
userService.delete(id);
}
}
```
这样,一个简单的 Spring Boot + Mybatis 示例就完成了。你可以使用 Postman 或者浏览器访问 http://localhost:8080/users/{id} 等接口测试。
阅读全文