블로그

spring repository 확장하기 with jpa, querydsl

JpaRepository 상속하는 repository interface 생성자동으로 빈 등록됨해당 repository는 의존주입 시 사용되는 repository public interface BoardRepository extends JpaRepository<Board, Long> {}   Querydsl을 사용하는 Custom Repository 생성 커스텀 리포지터리 interface 생성 public interface BoardRepositoryCustom { List<Object> findAll(); void updateAll(List<Long> ids, Boolean updatedStatus); } BoardRepository(JpaRepository)가 생성힌 Custom repository 또한 상속받도록 추가 public interface BoardRepository extends JpaRepository<Board, Long>, BoardRepositoryCustom {}   커스텀 리포지터리 확장 클래스 생성JPAQueryFactory는 별도로 빈등록 필요네이밍 시 repository + Impl 규칙을 사용하면 자동으로 빈등록 됨. @RequiredArgsConstructor public class BoardRepositoryImpl implements BoardRepositoryCustom{ private final EntityManager em; private final JPAQueryFactory jpaQueryFactory; @Override public List<BoardResponseDto> findAll(){ List<BoardResponseDto> results = jpaQueryFactory.select( Projections.constructor(BoardResponseDto.class, board.id, board.boardType, board.title, board.content, user.id, user.name, board.recruitingCnt, board.startDate, board.endDate, board.createdDate ) ) .from(board) .innerJoin(board.writer, user) .fetch(); return new results; } @Override public void updateAll(List<Long> ids, Boolean updatedStatus) { jpaQueryFactory.update(board) .set(board.updatedStatus, updatedStatus) .where(board.id.in(ids)) .execute(); em.flush(); em.clear(); } }  

다형성interfaceJPAQuerydsl확장repository

채널톡 아이콘