게시물을 등록하는 코드를 작성하겠습니다.
게시물 전체조회와 마찬가지로 UserJpaResource에 작성하겠습니다.
createPostForUser()package study.rest.webservices.restfulwebservices.user;
import jakarta.validation.Valid;
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 study.rest.webservices.restfulwebservices.jpa.PostRepository;
import study.rest.webservices.restfulwebservices.jpa.UserRepository;
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
public class UserJpaResource {
private UserRepository repository;
private PostRepository postRepository;
public UserJpaResource(UserRepository repository, PostRepository postRepository) {
this.repository = repository;
this.postRepository = postRepository;
}
//GET /users
@GetMapping("/jpa/users")
public List<User> retrieveAllUsers() {
return repository.findAll();
}
//EntityModel
//WebMvcLinkBuilder
@GetMapping("/jpa/users/{id}")
public EntityModel<User> retrieveUser(@PathVariable("id") int id) {
Optional<User> user = repository.findById(id);
if (user.isEmpty()) {
throw new UserNotFoundException("id:" + id);
}
EntityModel<User> entityModel = EntityModel.of(user.get());
WebMvcLinkBuilder link = linkTo(methodOn(this.getClass()).retrieveAllUsers());
entityModel.add(link.withRel("all-users"));
return entityModel;
}
@DeleteMapping("/jpa/users/{id}")
public void deleteUser(@PathVariable("id") int id) {
repository.deleteById(id);
}
@GetMapping("/jpa/users/{id}/posts")
public List<Post> retrievePostsForUser(@PathVariable("id") int id) {
Optional<User> user = repository.findById(id);
if (user.isEmpty()) {
throw new UserNotFoundException("id:" + id);
}
return user.get().getPosts();
}
//POST /users
@PostMapping("/jpa/users")
public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
User savedUser = repository.save(user);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("{id}").buildAndExpand(savedUser.getId()).toUri();
return ResponseEntity.created(location).build();
}
@PostMapping("/jpa/users/{id}/posts")
public ResponseEntity<Object> createPostForUser(@PathVariable("id") int id, @Valid @RequestBody Post post) {
Optional<User> user = repository.findById(id);
if (user.isEmpty()) {
throw new UserNotFoundException("id:" + id);
}
post.setUser(user.get());
Post savedPost = postRepository.save(post);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}/posts")
.buildAndExpand(savedPost.getId())
.toUri();
return ResponseEntity.created(location).build();
}
}