用springboot mybatis写一个增删改查
时间: 2023-09-10 11:14:27 浏览: 80
1. 首先需要在pom.xml文件中添加依赖:
```xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
```
2. 在application.properties文件中配置数据库连接信息:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
3. 创建实体类User:
```java
public class User {
private Integer id;
private String name;
private Integer age;
// getter和setter方法省略
}
```
4. 创建Mapper接口UserMapper:
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(Integer 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(Integer id);
}
```
5. 在application类中添加MapperScan注解:
```java
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
6. 在Controller中注入UserMapper并实现增删改查:
```java
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/user/{id}")
public User findById(@PathVariable("id") Integer id) {
return userMapper.findById(id);
}
@PostMapping("/user")
public void save(User user) {
userMapper.save(user);
}
@PutMapping("/user")
public void update(User user) {
userMapper.update(user);
}
@DeleteMapping("/user/{id}")
public void delete(@PathVariable("id") Integer id) {
userMapper.delete(id);
}
}
```
阅读全文