下面是一个使用Spring Boot实现增删改查的示例代码:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
private String email;
// getters and setters
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public List<User> getAllUsers() {
return userRepository.findAll();
}
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
public User createUser(User user) {
return userRepository.save(user);
}
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
public User updateUser(Long id, User user) {
User existingUser = userRepository.findById(id).orElse(null);
if (existingUser != null) {
existingUser.setName(user.getName());
existingUser.setAge(user.getAge());
existingUser.setEmail(user.getEmail());
return userRepository.save(existingUser);
} else {
return null;
}
}
}
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@PostMapping("/")
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.updateUser(id, user);
}
}
现在,你可以使用以下API来进行增删改查操作:
请注意,以上代码只是一个示例,你可以根据具体需求进行适当的修改。