[Spring] 영속성 컨텍스트을 통한 데이터 조회

류재성's avatar
Mar 14, 2024
[Spring] 영속성 컨텍스트을 통한 데이터 조회
 

1. 영속성 객체를 사용한 데이터 조회

 
네이티브쿼리 사용
public Board findById(int id) { Query query = em.createNativeQuery("select * from board_tb where id =?",Board.class); query.setParameter(1,id); Board board = (Board) query.getSingleResult(); }
 
Persistence Context 사용
public Board findById(int id){ Board board = em.find(Board.class,id); return board; }
 
 
notion image
 
💡
ID가 1번인 데이터를 조회하면 PC에 데이터가 없기 때문에 DB에서 데이터를 조회한다.
 
@Test public void fintById_test(){ int id = 1; boardReposiroty.findById(id); }
 
notion image
 
쿼리가 한번 전송된다.
 
 
notion image
💡
만약 ID가 1번인 데이터를 한 번 더 조회하면 PC 메모리에 데이터가 남아있기 때문에 DB에서 조회하지 않고 캐싱된다.
 
@Test public void fintById_test(){ int id = 1; boardReposiroty.findById(id); boardReposiroty.findById(id); }
 
notion image
 
이미 조회된 데이터가 있기 때문에 쿼리를 날리지 않고 캐싱된다.
 

2. 컨트롤러

 
@GetMapping("/board/{id}") public String detail(@PathVariable Integer id,HttpServletRequest request) { // int 를 쓰면 값이 없으면 0, Integer 를 넣으면 값이 없을 때 null 값이 들어옴. Board board = boardPersistRepository.findById(id); request.setAttribute("board",board); return "board/detail";
 
조회된 board 객체를 requset 객체에 담아 전달한다.

3. View 확인하기

 
<div class="container p-5"> <!-- 수정삭제버튼 --> <div class="d-flex justify-content-end"> <a href="/board/{{board.id}}/update-form" class="btn btn-warning me-1">수정</a> <form action="/board/{{board.id}}/delete" method="post"> <button class="btn btn-danger">삭제</button> </form> </div> <div class="d-flex justify-content-end"> <b>작성자</b> : {{board.username}} </div> <!-- 게시글내용 --> <div> <h2><b>{{board.title}}</b></h2> <hr /> <div class="m-4 p-2"> {{board.content}} </div> </div>
 
notion image
Share article
RSSPowered by inblog