Service는 트랙잭션과, 도메인 간 순서 보장의 역할만 한다.
package com.momenting.book.springboot.web.dto;
import com.momenting.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();
}
}
package com.momenting.book.springboot.service.posts;
import com.momenting.book.springboot.domain.posts.Posts;
import com.momenting.book.springboot.domain.posts.PostsRepository;
import com.momenting.book.springboot.web.dto.PostsSaveRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@RequiredArgsConstructor
@Service
public class PostsService {
private final PostsRepository postsRepository;
@Transactional
public Long save(PostsSaveRequestDto requestDto) {
return postsRepository.save(requestDto.toEntity()).getId();
}
}
package com.momenting.book.springboot.web;
import com.momenting.book.springboot.service.posts.PostsService;
import com.momenting.book.springboot.web.dto.PostsSaveRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@RequiredArgsConstructor
@RestController
public class PostsApiController {
private final PostsService postsService;
@PostMapping("api/v1/posts")
public Long save (@RequestBody PostsSaveRequestDto requestDto) {
return postsService.save(requestDto);
}
}