springboot写一个删除接口
时间: 2024-01-31 15:02:45 浏览: 47
用SpringBoot写的学生成绩管理系统.zip
5星 · 资源好评率100%
@RestController
public class DeleteController {
@Autowired
private UserService userService;
@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
User user = userService.getUserById(id);
if (user == null) {
return ResponseEntity.notFound().build();
}
userService.deleteUser(user);
return ResponseEntity.noContent().build();
}
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public User getUserById(Long id) {
Optional<User> optionalUser = userRepository.findById(id);
return optionalUser.orElse(null);
}
@Override
public void deleteUser(User user) {
userRepository.delete(user);
}
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
阅读全文