QueryDsl 이란?

이상수·2022년 12월 6일
0

TIL_Database

목록 보기
3/3

1. QueryDsl 이란?

  • 오픈소스 프레임워크, JPQL을 java코드로 작성할 수 있또록 하는 라이브러리
  • Jpa로 해결하기 어려운 복잡한 쿼리/동적 쿼리를 해결할 수 있음
  • ★ 자바코드로 작성하기 때문에 문법오류를 컴파일 시점에 잡아낼 수 있다.
  • 동적인 쿼리작성이 편리하고, IDE의 도움을 받아 제약 조건등을 메서드 추출을 통해 재사용 할 수 있다.
  • select, from, where등 쿼리 작성에 필요한 키워드를 메서드 형식으로 제공한다.

2. 사용 예시

1). EntityManager 주입받기

  • QueuryDsl 이 query를 생성할 수 있도록 EntityManager를 주입
@Configuration
public class QuerydslConfiguration {
    @Autowired
    EntityManager em;

    @Bean
    public JPAQueryFactory jpaQueryFactory() {
       return new JPAQueryFactory(em);
    }
}

2). RoomRepositoryCustom 생성 및 구현

public interface RoomRepositoryCustom {

    Page<RoomOfList> searchAll(FieldsOfRoomList fieldsOfRoomList, Pageable pageable);
}

public interface RoomRepository extends JpaRepository<Room, Long>, RoomRepositoryCustom {

}

3). RoomRepositoryImpl 구현체 구현


@RequiredArgsConstructor
public class RoomRepositoryImpl implements RoomRepositoryCustom{

    private final JPAQueryFactory queryFactory;
    private final ParsingEntityUtils parsingEntityUtils;

    @Override
    public Page<RoomOfList> searchAll(FieldsOfRoomList fieldsOfRoomList, Pageable pageable) {

        List<Room> result = queryFactory
                .selectFrom(room)
                .leftJoin(room.tags, tag1).fetchJoin()
                .where(eqInterests(
                    fieldsOfRoomList.getExercise()),
                    eqArea(fieldsOfRoomList.getArea()),
                    participateCount(fieldsOfRoomList.getParticipantCount(), fieldsOfRoomList.isContainNoAdmittance()),
                    betweenTime(fieldsOfRoomList.getStartAppointmentDate(), fieldsOfRoomList.getEndAppointmentDate(), fieldsOfRoomList.isContainTimeClosing()),
                    eqTitle(fieldsOfRoomList.getRoomTitle()),
                    eqContent(fieldsOfRoomList.getRoomContent())
                )
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .orderBy(sortRoomList(pageable))
                .fetch();


        return afterTreatment(result);

    }
}    

0. spring boot(gradle) 설정

// 1. queryDsl version 정보 추가
buildscript {
    ext {
        queryDslVersion = "5.0.0"
    }
}

plugins {
    id 'org.springframework.boot' version '2.6.3'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    // 2. querydsl plugins 추가
    id "com.ewerk.gradle.plugins.querydsl" version "1.0.10"
    id 'java'
}

//...

dependencies {
    // 3. querydsl dependencies 추가
    implementation "com.querydsl:querydsl-jpa:${queryDslVersion}"
    implementation "com.querydsl:querydsl-apt:${queryDslVersion}"
    //...
}

test {
    useJUnitPlatform()
}

/*
 * queryDSL 설정 추가
 */
// querydsl에서 사용할 경로 설정
def querydslDir = "$buildDir/generated/querydsl"
// JPA 사용 여부와 사용할 경로를 설정
querydsl {
    jpa = true
    querydslSourcesDir = querydslDir
}
// build 시 사용할 sourceSet 추가
sourceSets {
    main.java.srcDir querydslDir
}
// querydsl 컴파일시 사용할 옵션 설정
compileQuerydsl{
    options.annotationProcessorPath = configurations.querydsl
}
// querydsl 이 compileClassPath 를 상속하도록 설정
configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
    querydsl.extendsFrom compileClasspath
}
profile
Will be great Backend-developer

0개의 댓글