[Querydsl] querydsl 학습_1

2020. 8. 19. 19:21개발/DBMS

반응형

목적: REST API 서버 개발을 위한 사전 학습 과제 중 Querydsl 관련 주차 별 학습 자료 공유

학습 계획

주차학습 내용진행도

주차

학습 내용

진행도

1

소개 및 프로젝트 설정

100%

2

기본 문법 (구조, 검색, 정렬, 페이징)
haepyung88.tistory.com/227

100%

3

중급 문법 (DTO 조회, 동적 쿼리)
haepyung88.tistory.com/228

100%

4

활용 -1 (동적 쿼리 최적화), 활용 -2 (페이징 최적화)

 

세부 학습 내용

[1주차]


1. 소개 및 프로젝트 설정

Querydsl 이란?

  • SQL, JPQL을 코드로 작성할 수 있도록 도와주는 빌더 API

  • Spring Data JPA 를 도와주는 API 중 한가지

 

기존 SQL, JPQL 의 문제점?

  • 쿼리는 문자열이다. 즉 Type-check 불가능

  • 쿼리를 실행 하는 시점에서 발견 할 수있다. (컬럼명 잘 못 쓴사람 손)

  • 동적 쿼리 작성하기가 너무 힘들다 (그래서 MyBatis 가 있지만 이것 조차도 어렵다)

사용 하는 이유?

  • 반복되는 CRUD 코딩을 아주 편하게 가능하다 (이건 JPA 도 가능). 즉 중요한 비지니스 로직 개발에 더 시간 투자가 가능하다.

  • 개발 생산성 증가

  • 동적 쿼리를 아주 편하게 JAVA 코딩 스타일로 만들 수 있다.

  • 쿼리 작성시 Type-check가 가능하다. 개발시 바로 확인 가능. 아니면 컴파일 시점에서 잡아 준다.

설정 방법

1. 프로젝트 적용 기술

  • spring boot 2.3.xx

  • java 14

  • gradle 5.xx

  • querydsl-jpa 4.3.1 & querydsl-apt:4.1.4

  • junit5

2. build.gradle 파일 설정

plugins {
    id 'org.springframework.boot' version '2.3.3.RELEASE'
    id 'io.spring.dependency-management' version '1.0.10.RELEASE'
    id "com.ewerk.gradle.plugins.querydsl" version "1.0.10"// querydsl 사용을 위한 플러그인
    id 'java'
}

group = 'me.study'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '14'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'com.querydsl:querydsl-jpa' // querydsl jpa 설
    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'com.h2database:h2'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

test {
    useJUnitPlatform()
}

//querydsl 추가 시작
def querydslDir = "$buildDir/generated/querydsl"

querydsl {
    jpa = true
    querydslSourcesDir = querydslDir
}

sourceSets {
    main.java.srcDir querydslDir
}

configurations {
    querydsl.extendsFrom compileClasspath
}

compileQuerydsl {
    options.annotationProcessorPath = configurations.querydsl
}
//querydsl 추가 끝

 

 

3. SAMPLE ENTITY & REPOSITORY 생성

  • entity

@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
@Entity
public class Account {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @Builder
    public Account (Long id, String name) {
        this.id = id;
        this.name = name;
    }
}
  • repository

import me.study.querydslsample.damain.Account;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;

public interface AccountRepository extends JpaRepository<Account, Long>, QuerydslPredicateExecutor<Account> {
}

 

 

4. Querydsl 사용을 위한 빌드 방법

이제 사전 준비는 정말로 다 끝났다. 실제 사용을 위한 빌드를 진행해 보자

4-1. 위 설정을 다 했다면 gradle 의 Tasks set 중 others 를 보면 “compileQuerydsl” 이라는 컴파일러 실행

해당 이미지 중 ‘complieQuerydsl’ 실행

 

실행 하면 해당 위치에 QAccount 라는 파일이 생성

 

 

5. 테스트 및 확인

@SpringBootTest
@Transactional
class QuerydslSampleApplicationTests {

    @Autowired
    AccountRepository accountRepository;

    @Autowired
    EntityManager em;

    @Test
    void contextLoads() {

        Account account = Account.builder().id(1L).name("TEST").build();
        accountRepository.save(account);

        JPAQueryFactory query = new JPAQueryFactory(em);
        QAccount qAccount = QAccount.account;
        Account result = query.selectFrom(qAccount)
                .where(qAccount.name.eq("TEST"))
                .fetchOne();

        Assertions.assertEquals(account.getId(), result.getId());
    }
}

위 코드는 아주 단순한 테스트 코드다. 우리가 집중해서 봐야할 것은 Line 17 ~21 라인이다.

해당 부분이 querydsl의 문법을 사용한 쿼리문으로 실제 쿼리를 확인해 보면 아래와 같은 쿼리가 날라가는 것을 확인 할 수 있다.

    /* select
        account 
    from
        Account account 
    where
        account.name = ?1 */ select
            account0_.id as id1_0_,
            account0_.name as name2_0_ 
        from
            account account0_ 
        where
            account0_.name=?

 

 

해당 쿼리는 단순 한 쿼리문이라 많은 차이가 없을 수 있으니 JAVA 코드를 짜듯 해당 도메인의 컬럼을 가져와서 쿼리문을 쉽게 작성 할 수있다.

 

소스: github.com/haepyung/querydsl-sample.git

[1주차]-end


 

반응형

'개발 > DBMS' 카테고리의 다른 글

[Querydsl] querydsl 학습_4  (0) 2020.11.23
[Querydsl] querydsl 학습_3  (0) 2020.09.04
[Querydsl] querydsl 학습_2  (0) 2020.08.28
[Querydsl] querydsl 적용시 주의점  (1) 2019.11.08