你扮演一个高级程序员,写一个基础springboot和mybatis框架的写一个CRUD的脚手架
时间: 2023-06-24 15:06:25 浏览: 160
好的,我可以帮您写一个基于Spring Boot和MyBatis框架的CRUD脚手架。以下是步骤:
1. 创建一个新的Spring Boot项目
使用Spring Initializr创建一个新的Spring Boot项目,并添加所需的依赖项:
- Spring Web
- MyBatis
- MySQL Driver
2. 配置数据库连接
在application.properties文件中配置数据库连接信息:
```
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
3. 创建实体类和Mapper接口
在src/main/java目录下创建一个实体类和一个Mapper接口,例如:
```
// 实体类
public class User {
private Long id;
private String name;
private Integer age;
// 省略getter和setter方法
}
// Mapper接口
@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 deleteById(Long id);
}
```
4. 创建Service和Controller
在src/main/java目录下创建一个Service和一个Controller,例如:
```
// Service
@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 deleteById(Long id) {
userMapper.deleteById(id);
}
}
// Controller
@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 deleteById(@PathVariable Long id) {
userService.deleteById(id);
}
}
```
5. 测试API
启动项目并测试API:
- GET http://localhost:8080/users/{id}:根据ID查询用户
- POST http://localhost:8080/users/:添加用户
- PUT http://localhost:8080/users/:更新用户
- DELETE http://localhost:8080/users/{id}:删除用户
以上就是一个简单的Spring Boot和MyBatis框架的CRUD脚手架。
阅读全文