下面是一個(gè)使用Spring Boot實(shí)現(xiàn)增刪改查的示例代碼:
@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);
}
}
現(xiàn)在,你可以使用以下API來(lái)進(jìn)行增刪改查操作:
請(qǐng)注意,以上代碼只是一個(gè)示例,你可以根據(jù)具體需求進(jìn)行適當(dāng)?shù)男薷摹?/p>