public interface MemberRepository extends JpaRepository<Member, Long> {
List<Member> findByUsername(String username);
}
public interface MemberRepositoryCustom {
List<MemberTeamDTO> search(MemberSearchCondition condition);
}
@RequiredArgsConstructor
public class MemberRepositoryCustomImpl implements MemberRepositoryCustom {
private final JPAQueryFactory jpaQueryFactory;
@Override
public List<MemberTeamDTO> search(MemberSearchCondition condition) {
return jpaQueryFactory
.select(new QMemberTeamDTO(
member.id,
member.username,
member.age,
team.id,
team.name
))
.from(member)
.leftJoin(member.team, team)
.where(
usernameEquals(condition.getUsername()),
teamNameEquals(condition.getTeamName()),
ageGoe(condition.getAgeGoe()),
ageLoe(condition.getAgeLoe())
)
.fetch();
}
private BooleanExpression usernameEquals(String username) {
return hasText(username) ? member.username.eq(username) : null;
}
private BooleanExpression teamNameEquals(String teamName) {
return hasText(teamName) ? team.name.eq(teamName) : null;
}
private BooleanExpression ageGoe(Integer ageGoe) {
return ageGoe != null ? member.age.goe(ageGoe) : null;
}
private BooleanExpression ageLoe(Integer ageLoe) {
return ageLoe != null ? member.age.loe(ageLoe) : null;
}
}
public interface MemberRepository extends JpaRepository<Member, Long>, MemberRepositoryCustom {
List<Member> findByUsername(String username);
}
@DataJpaTest
@Import(QuerydslConfig.class)
class MemberRepositoryTest {
@Autowired
MemberRepository memberRepository;
@PersistenceContext
EntityManager em;
@BeforeEach
public void beforeEach() {
Team teamA = new Team("teamA");
Team teamB = new Team("teamB");
em.persist(teamA);
em.persist(teamB);
Member member1 = new Member("member1", 10, teamA);
Member member2 = new Member("member2", 20, teamA);
Member member3 = new Member("member3", 30, teamB);
Member member4 = new Member("member4", 40, teamB);
em.persist(member1);
em.persist(member2);
em.persist(member3);
em.persist(member4);
}
@Test
void searchByCustomRepository() {
//given
MemberSearchCondition memberSearchCondition = MemberSearchCondition.builder()
.teamName("teamB")
.ageGoe(20)
.ageLoe(40)
.build();
//when
List<MemberTeamDTO> memberTeamDTOS = memberRepository.search(memberSearchCondition);
//then
assertThat(memberTeamDTOS).extracting("username")
.containsExactly("member3", "member4");
}
}
댓글남기기