|
| 1 | +package com.webenius.springbootapp.controller; |
| 2 | + |
| 3 | +import org.springframework.web.bind.annotation.GetMapping; |
| 4 | +import org.springframework.web.bind.annotation.RestController; |
| 5 | +import com.webenius.springbootapp.model.User; |
| 6 | +import com.webenius.springbootapp.repository.UserRepository; |
| 7 | +import org.springframework.beans.factory.annotation.Autowired; |
| 8 | +import org.springframework.web.bind.annotation.*; |
| 9 | + |
| 10 | +import java.util.List; |
| 11 | + |
| 12 | +@RestController |
| 13 | +@RequestMapping("/api/users") |
| 14 | +public class UserController { |
| 15 | + |
| 16 | + @Autowired |
| 17 | + private UserRepository userRepository; |
| 18 | + |
| 19 | + @GetMapping |
| 20 | + public List<User> getAllUsers() { |
| 21 | + return userRepository.findAll(); |
| 22 | + } |
| 23 | + |
| 24 | + @PostMapping |
| 25 | + public User createUser(@RequestBody User user) { |
| 26 | + return userRepository.save(user); |
| 27 | + } |
| 28 | + |
| 29 | + @GetMapping("/{id}") |
| 30 | + public User getUserById(@PathVariable Long id) { |
| 31 | + return userRepository.findById(id).orElseThrow(() -> new RuntimeException("User not found with id " + id)); |
| 32 | + } |
| 33 | + |
| 34 | + @PutMapping("/{id}") |
| 35 | + public User updateUser(@PathVariable Long id, @RequestBody User userDetails) { |
| 36 | + User user = userRepository.findById(id).orElseThrow(() -> new RuntimeException("User not found with id " + id)); |
| 37 | + user.setName(userDetails.getName()); |
| 38 | + user.setEmail(userDetails.getEmail()); |
| 39 | + return userRepository.save(user); |
| 40 | + } |
| 41 | + |
| 42 | + @DeleteMapping("/{id}") |
| 43 | + public String deleteUser(@PathVariable Long id) { |
| 44 | + userRepository.deleteById(id); |
| 45 | + return "User deleted with id " + id; |
| 46 | + } |
| 47 | +} |
0 commit comments