Querydsl - 프로젝트 환경설정

YulHee Kim·2022년 1월 3일
0

Querydsl

목록 보기
1/6

김영한님의 '실전! Querydsl'을 수강하며 정리하는 글입니다

프로젝트 환경설정

✔️ Querydsl 사용하는 이유

Spring boot와 Spring data JPA 기술을 조합해서 사용할 때 복잡한 쿼리와 동적 쿼리를 해결하지 못하는 한계점이 존재합니다. 실무에선 복잡한 쿼리를 자주 다루고 검색 조건에 따라 복잡한 동적 쿼리를 생성해야할 때가 많이 있습니다. 이런 문제점을 해결해주는 것이 바로 Querydsl입니다.

  • Querydsl은 쿼리를 자바 코드로 작성하게 해줍니다.
  • 자바 코드로 작성하기 때문에 문법 오류를 컴파일 시점에 알 수 있습니다.
  • 동적 쿼리 문제를 깔끔하게 해결할 수 있습니다.
  • 코드는 자바로 작성하지만 문법은 SQL과 거의 비슷합니다.
  • 그렇기 때문에 복잡한 쿼리도 쉽게 작성할 수 있습니다.

장점이 참 많습니다. 또한 실제 백엔드 개발자에게 디비 쿼리문을 작성하는건 굉장히 많은 업무 비중을 차지하기에 querydsl을 더 깊게 공부해보고자 합니다 😆

✔️ 프로젝트 생성

사용기능 : Spring Web, jpa, h2, lombok

✔️ Querydsl설정

먼저 프로젝트 생성 후, Querydsl을 사용하기 위한 설정을 해보겠습니다.
build.gradle에 querydsl 설정을 추가했습니다.

build.gradle

buildscript {
	ext {
		queryDslVersion = "5.0.0"
	}
}

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

group = 'study'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
	compileOnly {
		extendsFrom annotationProcessor
	}
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'org.springframework.boot:spring-boot-starter-web'

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

	compileOnly 'org.projectlombok:lombok'
	runtimeOnly 'com.h2database:h2'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
	useJUnitPlatform()
}

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

querydsl {
	jpa = true
	querydslSourcesDir = querydslDir
}
sourceSets {
	main.java.srcDir querydslDir
}
compileQuerydsl{
	options.annotationProcessorPath = configurations.querydsl
}

configurations {
	compileOnly {
		extendsFrom annotationProcessor
	}
	querydsl.extendsFrom compileClasspath
}
//querydsl 추가 끝

✔️ Querydsl 검증

검증용 엔티티 생성

package study.querydsl.entity;

import lombok.Getter;
import lombok.Setter;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
@Getter @Setter
public class Hello {

    @Id @GeneratedValue
    private Long id;
}

검증용 Q타입 생성을 위해 Gradle -> Tasks -> other -> compileQuerydsl을 두번 클릭해줍니다.

테스트 케이스로 실행 검증

package study.querydsl;

import com.querydsl.jpa.impl.JPAQueryFactory;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Commit;
import org.springframework.transaction.annotation.Transactional;
import study.querydsl.entity.Hello;
import study.querydsl.entity.QHello;

import javax.persistence.EntityManager;

import static org.assertj.core.api.Assertions.*;

@SpringBootTest
@Transactional
@Commit
class QuerydslApplicationTests {

	@Autowired
	EntityManager em;

	@Test
	void contextLoads() {
		Hello hello = new Hello();
		em.persist(hello);

		JPAQueryFactory query = new JPAQueryFactory(em);
		QHello qHello = new QHello("h");

		Hello result = query
				.selectFrom(qHello)
				.fetchOne();

		assertThat(result).isEqualTo(hello);
        assertThat(result.getId()).isEqualTo(hello.getId());
	}

}

Querydsl Q타입과 lombok 모두 정상 동작하는 것을 확인할 수 있습니다.

✔️ 라이브러리 살펴보기

Querydsl 라이브러리

  • querydsl-apt: Querydsl 관련 코드 생성 기능을 제공합니다.
  • querydsl-jpa: querydsl 라이브러리입니다.

그 다음 application.yml에 jPA와 DB 설정도 해주었습니다.

profile
백엔드 개발자

0개의 댓글