๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ–ฅ๏ธ ๋ฐฑ์—”๋“œ/SpringBoot

[Querydsl] SpringDataJPA + Querydsl + ์‚ฌ์šฉ์ž ์ •์˜ ์ธํ„ฐํŽ˜์ด์Šค

by OR15A 2024. 1. 7.
์‚ฌ์šฉ์ž ์ •์˜ ์ธํ„ฐํŽ˜์ด์Šค ์ž‘์„ฑ
public interface MemberRepositoryCustom {
	 List<MemberTeamDto> search(MemberSearchCondition condition);
}
  • SpringDataJPA๊ฐ€ ์ œ๊ณตํ•˜๋Š” ๋ฉ”์„œ๋“œ ์™ธ์— ํ•„์š”ํ•œ ๋ฉ”์„œ๋“œ๊ฐ€ ์žˆ์„ ๋•Œ

 

 

์‚ฌ์šฉ์ž ์ •์˜ ์ธํ„ฐํŽ˜์ด์Šค ๊ตฌํ˜„
public class MemberRepositoryImpl implements MemberRepositoryCustom {
     private final JPAQueryFactory queryFactory;
     public MemberRepositoryImpl(EntityManager em) {
         this.queryFactory = new JPAQueryFactory(em);
     }
     
     @Override
     //ํšŒ์›๋ช…, ํŒ€๋ช…, ๋‚˜์ด(ageGoe, ageLoe)
     public List<MemberTeamDto> search(MemberSearchCondition condition) {
         return queryFactory.select(new QMemberTeamDto(member.id,
                                                       member.username,
                                                       member.age,
                                                       team.id,
                                                       team.name))
                             .from(member)
                             .leftJoin(member.team, team)
                             .where(usernameEq(condition.getUsername()),
                                    teamNameEq(condition.getTeamName()),
                                    ageGoe(condition.getAgeGoe()),
                                    ageLoe(condition.getAgeLoe()))
                             .fetch();
     }
     
     private BooleanExpression usernameEq(String username) {
         return isEmpty(username) ? null : member.username.eq(username);
     }
     
     private BooleanExpression teamNameEq(String teamName) {
         return isEmpty(teamName) ? null : team.name.eq(teamName);
     }
     
     private BooleanExpression ageGoe(Integer ageGoe) {
         return ageGoe == null ? null : member.age.goe(ageGoe); 
     }
         
     private BooleanExpression ageLoe(Integer ageLoe) {
         return ageLoe == null ? null : member.age.loe(ageLoe);
     }
}

 

 

 

์Šคํ”„๋ง ๋ฐ์ดํ„ฐ ๋ฆฌํฌ์ง€ํ† ๋ฆฌ์— ์‚ฌ์šฉ์ž ์ •์˜ ์ธํ„ฐํŽ˜์ด์Šค ์ƒ์†
public interface MemberRepository extends JpaRepository<Member, Long>, MemberRepositoryCustom {
     List<Member> findByUsername(String username);
}