写一个spring boot整合mybatis进行增删改查的源码
时间: 2023-11-28 12:48:29 浏览: 101
springboot+mybatis实现增删改查(视频+源码)
好的,下面是一个简单的示例代码:
首先,pom.xml中需要添加以下依赖:
```xml
<dependencies>
<!-- Spring Boot MyBatis Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
</dependencies>
```
接着,在application.properties中配置数据库连接信息:
```properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
```
然后,创建一个实体类User:
```java
public class User {
private Long id;
private String username;
private String password;
// 省略 getter 和 setter 方法
}
```
接着,创建一个Mapper接口UserMapper:
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM t_user WHERE id = #{id}")
User findById(Long id);
@Insert("INSERT INTO t_user(username, password) VALUES(#{username}, #{password})")
void save(User user);
@Update("UPDATE t_user SET username = #{username}, password = #{password} WHERE id = #{id}")
void update(User user);
@Delete("DELETE FROM t_user WHERE id = #{id}")
void delete(Long id);
}
```
最后,创建一个Controller类UserController:
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/{id}")
public User findById(@PathVariable Long id) {
return userMapper.findById(id);
}
@PostMapping("")
public void save(@RequestBody User user) {
userMapper.save(user);
}
@PutMapping("")
public void update(@RequestBody User user) {
userMapper.update(user);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
userMapper.delete(id);
}
}
```
这样,我们就完成了一个简单的Spring Boot整合Mybatis进行增删改查的示例。
阅读全文