공부/스프링 부트와 AWS로 혼자 구현하는 웹 서비스
3장 2) 등록
소갱
2021. 12. 9. 17:31
web / PostsApiController.class
@RequiredArgsConstructor
@RestController
public class PostsApiController {
private final PostsService postsService;
@PostMapping("/api/v1/posts")
public Long save(@RequestBody PostsSaveRequestDto requestDto){
return postsService.save(requestDto);
}
}
weblayer 계층에 있는 Controller, 홈페이지에서 등록한 정보를 가져온다.
web / dto / PostsSaveRequestDto
package com.sogang.book.springboot.web.dto;
import com.sogang.book.springboot.domain.posts.Posts;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
public class PostsSaveRequestDto {
private String title;
private String content;
private String author;
@Builder
public PostsSaveRequestDto(String title, String content, String author) {
this.title = title;
this.content = content;
this.author = author;
}
public Posts toEntity(){
return Posts.builder()
.title(title)
.content(content)
.author(author)
.build();
}
}
service / posts / PostsService.class
@RequiredArgsConstructor
@Service
public class PostsService {
private final PostsRepository postsRepository;
@Transactional
public Long save(PostsSaveRequestDto requestDto){
return postsRepository.save(requestDto.toEntity()).getId();
}
}
ServiceLayer 계층에 있는 service, ApiController를 통해 얻어온 정보를 Repository로 보내준다.