17. 게시판 글쓰기v3

송민경's avatar
Mar 14, 2024
17. 게시판 글쓰기v3

1. View 보기

{{> /layout/header}} <div class="container p-5"> <!-- 요청을 하면 localhost:8080/board/save POST로 요청됨 title=사용자입력값&content=사용자값 --> <div class="card"> <div class="card-header"><b>글쓰기 화면입니다</b></div> <div class="card-body"> <form action="/board/save" method="post"> <div class="mb-3"> <input type="text" class="form-control" placeholder="Enter title" name="title"> </div> <div class="mb-3"> <textarea class="form-control" rows="5" name="content"></textarea> </div> <button type="submit" class="btn btn-primary form-control">글쓰기완료</button> </form> </div> </div> </div> {{> /layout/footer}}
 

2. BoardRequest 에 SaveDTO () 만들기

  • Board 에 생성자에 @Builder 달기
package shop.mtcoding.blog.board; import jakarta.persistence.*; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.CreationTimestamp; import shop.mtcoding.blog.user.User; import shop.mtcoding.blog.util.MyDateUtil; import java.sql.Timestamp; @NoArgsConstructor @Data // 변경되는 데이터에만 setter가 필요함 @Table(name = "board_tb") @Entity public class Board { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String title; private String content; // private String username; // username은 user_tb에도 있기에 외래키로 연관관계 맺어야 함 // @JoinColumn(name = "user_id") 직접 지정할 때 @ManyToOne(fetch = FetchType.LAZY) // ORM 할 것이기에 user 객체 필요 private User user; // DB에 컬럼명 : user_id (변수명_PK키) @CreationTimestamp // PC로 인해 DB에 INSERT될 때 날짜 주입 private Timestamp createdAt; @Builder public Board(Integer id, String title, String content, User user, Timestamp createdAt) { this.id = id; this.title = title; this.content = content; this.user = user; this.createdAt = createdAt; } public String getBoardDate(){ return MyDateUtil.timestampFormat(createdAt); } }
  • SaveDTO() 만들기
package shop.mtcoding.blog.board; import lombok.Data; import shop.mtcoding.blog.user.User; public class BoardRequest { @Data public static class SaveDTO { private String title; private String content; // DTO를 클라이언트로 부터 받아서, PC에 전달하기 위해 사용 // insert하는 DTO에서만 만들기 public Board toEntity(User user){ return Board.builder() .title(title) .content(content) .user(user) .build(); } } }
 

3. BoardRepository 에 save() 만들기

package shop.mtcoding.blog.board; import jakarta.persistence.EntityManager; import jakarta.persistence.Query; import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Repository; import shop.mtcoding.blog.user.User; import java.util.HashSet; import java.util.List; import java.util.Set; @RequiredArgsConstructor @Repository public class BoardRepository { private final EntityManager em; @Transactional public void save(Board board){ em.persist(board); } public List<Board> findAllV3() { String q1 = "select b from Board b order by b.id desc"; List<Board> boardList = em.createQuery(q1, Board.class).getResultList(); int[] userIds = boardList.stream().mapToInt(board -> board.getUser().getId()).distinct().toArray(); String q2 = "select u from User u where u.id in ("; for (int i = 0; i < userIds.length; i++) { if (i == userIds.length - 1) { q2 = q2 + userIds[i] + ")"; } else { q2 = q2 + userIds[i] + ","; } } List<User> userList = em.createQuery(q2, User.class).getResultList(); for (Board board : boardList) { for (User user : userList) { if (user.getId() == board.getUser().getId()) { board.setUser(user); } } } return boardList; // user가 채워져 있어야함. } public List<Board> findAllV2() { Query q1 = em.createQuery("select b from Board b order by b.id desc", Board.class); List<Board> boardList = q1.getResultList(); Set<Integer> userIds = new HashSet<>(); for (Board board : boardList) { userIds.add(board.getUser().getId()); } Query q2 = em.createQuery("select u from User u where u.id in :userIds", User.class); q2.setParameter("userIds", userIds); List<User> userList = q2.getResultList(); for (Board board : boardList) { for (User user : userList) { if (user.getId() == board.getUser().getId()) { board.setUser(user); } } } return boardList; } public List<Board> findAll() { // 다른 정보가 추가로 필요하면 조인하면 됨 - outer join일 때 outer는 생략 가능 Query query = em.createQuery("select b from Board b order by b.id desc", Board.class); return query.getResultList(); } public Board findByIdJoinUser(int id) { // on생략 가능, 알아서 pk연결해줌 Query query = em.createQuery("select b from Board b join fetch b.user u where b.id = :id", Board.class); query.setParameter("id", id); return (Board) query.getSingleResult(); } public Board findById(int id) { //id, title, content, user_id(이질감), created_at Board board = em.find(Board.class, id); return board; } }
 

4. BoardController 에 save 수정하

package shop.mtcoding.blog.board; import ch.qos.logback.core.model.Model; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import shop.mtcoding.blog.user.User; import java.lang.annotation.Native; import java.util.List; @RequiredArgsConstructor @Controller public class BoardController { private final BoardRepository boardRepository; private final HttpSession session; // @Transactional 트랜잭션 시간이 너무 길어져서 service에 넣어야함 @PostMapping("/board/{id}/update") public String update(@PathVariable Integer id) { return "redirect:/board/" + id; } @GetMapping("/board/{id}/update-form") public String updateForm(@PathVariable(name = "id") Integer id, HttpServletRequest request) { return "/board/update-form"; // 서버가 내부적으로 index를 요청 - 외부에서는 다이렉트 접근이 안됨 } @PostMapping("/board/{id}/delete") public String delete(@PathVariable Integer id) { // DTO 없이 구현 return "redirect:/"; } @GetMapping("/") public String index(HttpServletRequest request) { List<Board> boardList = boardRepository.findAll(); request.setAttribute("boardList", boardList); return "index"; // 서버가 내부적으로 index를 요청 - 외부에서는 다이렉트 접근이 안됨 } @PostMapping("/board/save") public String save(BoardRequest.SaveDTO reqDTO) { User sessionUser = (User) session.getAttribute("sessionUser"); boardRepository.save(reqDTO.toEntity(sessionUser)); return "redirect:/"; } @GetMapping("/board/save-form") public String saveForm() { return "board/save-form"; } @GetMapping("/board/{id}") public String detail(@PathVariable Integer id, HttpServletRequest request) { // Integer : 없으면 null, int : 0 Board board = boardRepository.findByIdJoinUser(id); request.setAttribute("board", board); return "board/detail"; } }
notion image
notion image
notion image
Share article

vosw1