스터디코딩
[게시판] 글 목록 출력하기(Read) 본문
1. list.html
<main class="container">
<div class="bg-light p-5 rounded">
<h1>게시판</h1>
<div>총건수 : <span th:text = "${#lists.size(boards)}"></span></div>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">번호</th>
<th scope="col">제목</th>
<th scope="col">작성자</th>
</tr>
</thead>
<tbody>
<tr th:each="board : ${boards}">
<td th:text="${board.id}">Mark</td>
<td th:text="${board.title}">Otto</td>
<td th:text="${board.content}">@mdo</td>
</tr>
</tbody>
</table>
<div class = "text-right">
<a type="button" class="btn btn-primary" th:href="@{/board/form}">쓰기</a>
</div>
</div>
</main>
2. BoardController.java
@GetMapping("/list")
public String list(Model model){ //파라메터값을 넘겨주고싶다면 model
List<Board> boards = boardRepositoryJPA.findAll();
model.addAttribute("boards",boards);
return "board/list";
}
3.BoardRepositoryJPA
@Repository
public class BoardRepositoryJPA {
private final EntityManager em;
@Autowired
public BoardRepositoryJPA(EntityManager em) {
this.em = em;
}
public List<Board> findAll() {
List<Board> result = em.createQuery("select m from Board m",Board.class).
getResultList();
return result;
}
}
4.Board
@Data //getter,setter를 lombok을 이용하여 외부에서 꺼내쓸 수 있게
@Entity //db연결을 위한 model클래스임을 알림.
public class Board { //table 이름과 같아야 한다.
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String content;
}
Comments