[Edit]
+
0
-
0

Spring Boot 2 - controller example that implements CRUD using JPA

9600
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @Controller public class UsersController { @Autowired private UsersRepository usersRepository; // http://localhost:8080/api/users // @GetMapping("/api/users") @Transactional(readOnly = true) public ResponseEntity<List<UserEntity>> getUsers() { return ResponseEntity.ok(this.usersRepository.findAll()); } // http://localhost:8080/api/users/1 // @GetMapping("/api/users/{id}") @Transactional(readOnly = true) public ResponseEntity<UserEntity> getUser(@PathVariable("id") Long userId) { return ResponseEntity.of(this.usersRepository.findById(userId)); } // echo '{"name":"john","email":"john@email.com"}' | curl -X POST -H "Content-Type: application/json" -d @- http://localhost:8080/api/user/create // @PostMapping("/api/user/create") @Transactional public ResponseEntity<UserEntity> createUser(@RequestBody UserEntity userEntity) { return ResponseEntity.ok(this.usersRepository.save(userEntity)); } // echo '{"name":"chris","email":"chris@email.com"}' | curl -X POST -H "Content-Type: application/json" -d @- http://localhost:8080/api/users/1/update // @PostMapping("/api/users/{id}/update") @Transactional public ResponseEntity<UserEntity> updateUser( @PathVariable("id") Long userId, @RequestBody UserEntity newUserEntity) { Optional<UserEntity> foundUserOptional = this.usersRepository.findById(userId); if (foundUserOptional.isPresent()) { UserEntity foundUserEntity = foundUserOptional.get(); foundUserEntity.setName(newUserEntity.getName()); foundUserEntity.setEmail(newUserEntity.getEmail()); this.usersRepository.save(foundUserEntity); } return ResponseEntity.of(foundUserOptional); } // http://localhost:8080/api/users/1/remove // @GetMapping("/api/users/{id}/remove") @Transactional public ResponseEntity<UserEntity> removeUser(@PathVariable("id") Long userId) { Optional<UserEntity> foundUserOptional = this.usersRepository.findById(userId); if (foundUserOptional.isPresent()) { this.usersRepository.deleteById(userId); } return ResponseEntity.of(foundUserOptional); } }