springboot增删改查
时间: 2023-06-28 22:16:00 浏览: 89
好的,我可以为您提供一个Spring Boot增删改查示例代码:
首先,我们需要创建一个实体类,例如User:
```
public class User {
private Integer id;
private String name;
private Integer age;
// getter和setter方法省略
}
```
然后,我们需要创建一个DAO层接口和对应的实现类,例如UserMapper和UserMapperImpl,用于操作数据库:
```
@Mapper
public interface UserMapper {
List<User> getAllUsers();
User getUserById(Integer id);
void addUser(User user);
void updateUser(User user);
void deleteUser(Integer id);
}
```
```
@Service
public class UserMapperImpl implements UserMapper {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List<User> getAllUsers() {
String sql = "SELECT * FROM user";
List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
return userList;
}
@Override
public User getUserById(Integer id) {
String sql = "SELECT * FROM user WHERE id = ?";
User user = jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(User.class));
return user;
}
@Override
public void addUser(User user) {
String sql = "INSERT INTO user(name, age) VALUES (?, ?)";
jdbcTemplate.update(sql, user.getName(), user.getAge());
}
@Override
public void updateUser(User user) {
String sql = "UPDATE user SET name = ?, age = ? WHERE id = ?";
jdbcTemplate.update(sql, user.getName(), user.getAge(), user.getId());
}
@Override
public void deleteUser(Integer id) {
String sql = "DELETE FROM user WHERE id = ?";
jdbcTemplate.update(sql, id);
}
}
```
最后,我们需要创建一个Controller类,例如UserController,用于接收请求和返回结果:
```
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/user")
public List<User> getAllUsers() {
return userMapper.getAllUsers();
}
@GetMapping("/user/{id}")
public User getUserById(@PathVariable("id") Integer id) {
return userMapper.getUserById(id);
}
@PostMapping("/user")
public void addUser(@RequestBody User user) {
userMapper.addUser(user);
}
@PutMapping("/user")
public void updateUser(@RequestBody User user) {
userMapper.updateUser(user);
}
@DeleteMapping("/user/{id}")
public void deleteUser(@PathVariable("id") Integer id) {
userMapper.deleteUser(id);
}
}
```
这样,我们就完成了Spring Boot的增删改查示例代码。
阅读全文