Added reading data from database using springboot

This commit is contained in:
grata
2023-04-27 09:55:31 +02:00
parent 6c7f9c6007
commit 1ea79fbda4
9 changed files with 112 additions and 36 deletions

View File

@@ -0,0 +1,66 @@
package ch.progetto152.controller;
import ch.progetto152.entity.User;
import ch.progetto152.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/get/all")
public ResponseEntity<List<User>> getAllUsers() {
List<User> users = userService.getAllUsers();
return new ResponseEntity<>(users, HttpStatus.OK);
}
@GetMapping("/get/{id}")
public ResponseEntity<User> getUserById(@PathVariable("id") Long id) {
User user = userService.getUserByIdService(id);
if (user != null) {
return new ResponseEntity<>(user, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@PostMapping("/create/{id}")
public ResponseEntity<User> createUser(@RequestBody User user) {
User createdUser = userService.createUser(user);
return new ResponseEntity<>(createdUser, HttpStatus.CREATED);
}
@PutMapping("/put/{id}")
public ResponseEntity<User> updateUser(@PathVariable("id") Long id, @RequestBody User user) {
User updatedUser = userService.updateUser(id, user);
if (updatedUser != null) {
return new ResponseEntity<>(updatedUser, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@DeleteMapping("/delete/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable("id") Long id) {
boolean deleted = userService.deleteUser(id);
if (deleted) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}