1. JPQL과 Native Query
createNativeQuery & createQuery 차이
em.createNativeQuery
- SQL 쿼리를 직접 실행. ex)
findByIdV2
메소드에 사용된 ”SELECTbt.id, bt.title,
… FROMboard_tb bt
INNER JOINuser_tb ut
ONbt.user_id
=ut.id
WHEREbt.id = ?
” → 반환된 데이터는 객체가 아닌 SQL 결과라서 직접 객체로 변환해야 함
em.createNativeQuery
- JPQL 사용.
- SQL과 달리 Entity 객체를 대상으로 함
- ex)
findByTitle
메소드에서 사용된 “SELECTb
FROMBoard b
WHEREb.title = :title"
→Board
Entity를 대상으로 함
- JPQL → Entity 속성(필드)을 사용하여 쿼리 작성
BoardRepository 코드 분석
public Board findByIdV2(int id) {
Query query = em.createNativeQuery("select bt.id, bt.title, bt.content, bt.user_id, bt.created_at, ut.id u_id, ut.username, ut.password, ut.email, ut.created_at u_created_at from board_tb bt inner join user_tb ut on bt.user_id = ut.id where bt.id = ?");
query.setParameter(1, id);
Object[] obs = (Object[]) query.getSingleResult();
...
return board;
}
createNativeQuery
→ SQL 문장 실행, 결과를Object[]
로 반환
- 이후 해당 배열을
Board
와User
객체에 수동으로 매핑 → Native SQL 사용 방식
전체 Repository 정리
BoardRepository는 EntityManager를 통해 DB에 접근하여 CRUD 작업 수행 메소드 정의
→ JPQL을 사용한 메소드는 Entity간 연관관계를 쉽게 처리
Share article