publicinterfaceMemberRepositoryextendsJpaRepository<Member,Long> { @Query(value ="select * from member where username = ?", nativeQuery =true)MemberfindByNativeQuery(String username);}
publicinterfaceMemberRepositoryextendsJpaRepository<Member,Long> { @Query(value ="SELECT m.member_id as id, m.username, t.name as teamName "+"FROM member m left join team t", countQuery ="SELECT count(*) from member", nativeQuery =true)Page<MemberProjection> findByNativeProjection(Pageable pageable);}
classMemberRepositoryTest { @TestvoidnativeQuery() {...// 인덱스가 0부터 시작하므로 0으로 조회한다.Page<MemberProjection> result =memberRepository.findByNativeProjection(PageRequest.of(0,10)); }}
SELECT m.member_id as id, m.username, t.name as teamNameFROM member mleft join team t limit10;SELECT count(*)from member;
동적 네이티브 쿼리
classExample {publicstaticvoidmain(String[] args) {String sql ="select m.username as username from member m";List<MemberDto> result =em.createNativeQuery(sql).setFirstResult(0).setMaxResults(10).unwrap(NativeQuery.class).addScalar("username").setResultTransformer(Transformers.aliasToBean(MemberDto.class)).getResultList(); }}
하이버네이트를 직접 활용한다.
스프링 JdbcTemplate, myBatis, jooq 같은 외부 라이브러리를 사용하는걸 추천한다.