finduser, createuser api
This commit is contained in:
@@ -1,11 +1,19 @@
|
||||
package com.example.restfulwebservice.user;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.hateoas.EntityModel;
|
||||
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
|
||||
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@@ -17,4 +25,35 @@ public class UserJpaController {
|
||||
public List<User> retrieveAllUsers() {
|
||||
return userRepository.findAll();
|
||||
}
|
||||
|
||||
@GetMapping("/users/{id}")
|
||||
public EntityModel<User> retrieveUser(@PathVariable int id) {
|
||||
Optional<User> user = userRepository.findById(id);
|
||||
if(user.isEmpty()){
|
||||
throw new UserNotFoundException(String.format("ID[%s] not found", id));
|
||||
}
|
||||
EntityModel<User> entityModel = new EntityModel<>(user.get());
|
||||
WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers());
|
||||
entityModel.add(linkTo.withRel("all-users"));
|
||||
|
||||
return entityModel;
|
||||
}
|
||||
|
||||
@DeleteMapping("/users/{id}")
|
||||
public void deleteUser(@PathVariable int id) {
|
||||
userRepository.deleteById(id);
|
||||
}
|
||||
|
||||
@PostMapping("/users")
|
||||
public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
|
||||
System.out.println(user);
|
||||
User savedUser = userRepository.save(user);
|
||||
|
||||
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
|
||||
.path("/{id}")
|
||||
.buildAndExpand(savedUser.getId())
|
||||
.toUri();
|
||||
|
||||
return ResponseEntity.created(location).build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
insert into user values(1, sysdate(), 'user1', 'test1', '700101-1111111');
|
||||
insert into user values(2, sysdate(), 'user2', 'test2', '800101-1231234');
|
||||
insert into user values(3, sysdate(), 'user3', 'test3', '900101-1121123');
|
||||
insert into user values(100000, sysdate(), 'user1', 'test1', '700101-1111111');
|
||||
insert into user values(100001, sysdate(), 'user2', 'test2', '800101-1231234');
|
||||
insert into user values(100002, sysdate(), 'user3', 'test3', '900101-1121123');
|
||||
Reference in New Issue
Block a user