PostController
@Slf4j
@RequiredArgsConstructor
@Controller
@RequestMapping("/post")
public class PostController {
private final PostService postService;
@GetMapping
public String read(Model model) {
List<Post> list = postService.read(); // 포스트 목록 검색
model.addAttribute("posts", list); // Model에 검색 결과를 세팅.
return "/post/read"; // view 이름 return
}
}
PoseService
@Slf4j
@RequiredArgsConstructor
@Service
public class PostService {
private final PostRepository postRepository;
// DB POSTS 테이블에서 전체 검색한 결과를 리턴:
@Transactional(readOnly = true) // 수정 안되게 readOnly
public List<Post> read() {
return postRepository.findByOrderByIdDesc();
}
}
PostRepository
public interface PostRepository extends JpaRepository<Post, Long> {
// id 내림차순 정렬
// select * from POSTS order by ID desc
List<Post> findByOrderByIdDesc();
}
read.html
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleat/layout"
layout:decorate="~{layout/base_layout}">
<main layout:fragment="main">
<table class="table table-hover text-center">
<thead>
<tr>
<th>NO</th>
<th>제목</th>
<th>작성자</th>
<th>수정 시간</th>
</tr>
</thead>
<tbody class="table-group-divider">
<tr th:each="post : ${posts}">
<!-- 변수 : ${model에 addAttribute 한 변수} -->
<td th:text="${post.id}"></td>
<td>
<a class="link-offset-2 link-underline-opacity-0 link-dark"
th:href="@{/post/detail?id={id} (id=${post.id})}"
th:text="${post.title}"></a>
</td>
<!-- 제목에 상세보기 링크 -->
<td th:text="${post.author}"></td>
<td th:text="${#temporals.format(post.modifiedTime, '
yyyy.MM.dd HH:mm:ss')}"></td>
</tr>
</tbody>
</table>
</main>