글에 글쓴이를 추가하는 로직들을 작성한다.
// domain - Article.java
@Entity
@Getter
@NoArgsConstructor
public class Article{
~ 생략 ~
@Column(name = "author", nullable = false)
private String author;
~ 생략 ~
@Builder
public Article(String author, String title, String content) {
this.author = author;
this.title = title;
this.content = content;
}
~ 생략 ~
}
// dto - AddArticleRequest.java
@NoArgsConstructor //기본 생성자 추가
@AllArgsConstructor // 모든 필드 값을 파라미터로 받는 생성자 추가
@Getter
public class AddArticleRequest { // 서비스계층에서 요청 받은 데이터를 엔티티로 생성.
private String title;
private String content;
public Article toEntity() { // 생성자를 사용해 객체 생성
return Article.builder()
.title(title)
.content(content)
.author(author)
.build(); // 빌더 패턴을 사용해 DTO를 엔티티로 만들어주는 메소드.
}
}
// service - BlogService.java
@RequiredArgsConstructor
@Service
public class BlogService {
~ 생략 ~
public Article save(AddArticleRequest request, String userName) {
return blogRepository.save(request.toEntity(userName));
}
~ 생략 ~
}
// controller - BlogApiController.java
@RequiredArgsConstructor
@RestController // HTTP Response Body에 객체 데이터를 JSON 형식으로 반환하는 컨트롤러
public class BlogApiController {
~ 생략 ~
@PostMapping("/api/articles")
public ResponseEntity<Article> addArticle(@RequestBody AddArticleRequest request, Principal principal) {
Article savedArticle = blogService.save(request, principal.getName());
return ResponseEntity.status(HttpStatus.CREATED)
.body(savedArticle);
}
~ 생략 ~
}
// dto - ArticleViewResponse.java
@NoArgsConstructor
@Getter
public class ArticleViewResponse {
~ 생략 ~
private String author;
public ArticleViewResponse(Article article) {
this.id = article.getId();
this.title = article.getTitle();
this.content = article.getContent();
this.createdAt = article.getCreatedAt();
this.author = article.getAuthor();
}
}
INSERT INTO article (title, content, author, created_at, updated_at) VALUES ('제목1', '내용1', 'user1', NOW(), NOW())
INSERT INTO article (title, content, author, created_at, updated_at) VALUES ('제목2', '내용2', 'user2', NOW(), NOW())
INSERT INTO article (title, content, author, created_at, updated_at) VALUES ('제목3', '내용3', 'user3', NOW(), NOW())
// resources - temlplates - article.html
~ 생략 ~
<header class="mb-4">
<h1 class="fw-bolder mb-1" th:text="${article.title}"></h1>
<div class="text-muted fst-italic mb-2" th:text="|Posted on ${#temporals.format(article.createdAt, 'yyyy-MM-dd HH:mm')} By ${article.author}|"></div>
~ 생략 ~