QueryDSL 사용법

공부는 혼자하는 거·2021년 11월 20일
0

Spring Tip

목록 보기
21/52

사전 mariaDB - JPA 셋팅

			<dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <scope>runtime</scope>
        </dependency>
			<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

application.yml

server:
  port: 8085
  servlet:
    context-path: /
    encoding:
      charset: utf-8
      enabled: true

spring:
	datasource:
	    driver-class-name: org.mariadb.jdbc.Driver
	    url: jdbc:mariadb://db.rigel.kr:3306/kang?serverTimezone=Asia/Seoul&useSSL=false&allowPublicKeyRetrieval=true
	    username: kang
	    password: 1234
	
	  jpa:
	    open-in-view: true
	    hibernate:
	      ddl-auto: update
	      naming:
	        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
	    show-sql: true
	
	logging:
	  level:
	    org.hibernate:
	      SQL: debug
	      type.descriptor.sql: trace

환경 셋팅

Maven 의존성 추가

<!--        <dependency>-->
<!--            <groupId>org.slf4j</groupId>-->
<!--            <artifactId>slf4j-log4j12</artifactId>-->
<!--            <version>1.6.1</version>-->
<!--        </dependency>-->

        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-apt</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
        </dependency>

------ 생략 -------

<plugin>
                <groupId>com.mysema.maven</groupId>
                <artifactId>apt-maven-plugin</artifactId>
                <version>1.1.3</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>process</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/generated-sources/java</outputDirectory>
                            <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

springBoot 최신 버전부터는 라이브러리 version을 생략해도 알맞게 갖고오나보다..

rum maven compile 실행

  • 가끔 intellij 버전에 따라 run maven compile 대신 Maven-> Generate Sources and Update Folders

https://media.vlpt.us/images/woo0_hooo/post/45c8d458-2107-42f7-b52c-97076aa2a1fc/Untitled.png

https://media.vlpt.us/images/woo0_hooo/post/3b8e926a-41ef-49c4-8c71-9148e8e7c815/Untitled%20(1).png

Java Config 설정

@Configuration
public class QueryDslConfig {

    @PersistenceContext
    private EntityManager entityManager;

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

}

→ 이제 프로젝트 어디에서든 JPAQuery 주입받아 querydsl 사용 가능

사용예시

기존 네이티브 쿼리

public interface UserRepository extends JpaRepository<User, Long>{

    @Query(value = "select * from User where procYn= 'N'", nativeQuery=true)
    List<User> mFindByProcyYnIsN();
}

QueryDsl로 변경

인터페이스 생성

public interface UserCustomRepository {

    List<User> findProcYNIsN();

}

상속 클래스 생성

@RequiredArgsConstructor
@Repository  //QueryDsl 용도
public class UserCustomRepositoryImpl implements UserCustomRepository{

    private final JPAQueryFactory jpaQueryFactory;

    @Override
    public List<User> findProcYNIsN() {

        //QUser user= new QUser("m"); //직접 만들기 싫다면 static 으로 import 하셔도 됩니다.

        return jpaQueryFactory
                .selectFrom(QUser.user)
                .where(QUser.user.procYn.eq("N"))
                .fetch();
    }

}
public interface UserRepository extends JpaRepository<User, Long>, UserCustomRepository {

    //queryDsl 사용하기 싫으시면 native Quey 사용하세요.
    @Query(value = "select * from User where procYn= 'N'", nativeQuery=true)
    List<User> mFindByProcyYnIsN();

}

사용

		@Transactional //UPDATE, DELETE 경우 @Transactional을 추가해줘야 에러가 발생 X
    public void test(){

        //전체는 찾지말고, procYn = n인 애들만 찾아서. y로 바꿔주자..

        List<User> users  = UserRepository.findProcYNIsN();
        //List<User> users  = UserRepository.mFindByProcyYnIsN();

    }

Gradle 사용시

    implementation 'com.querydsl:querydsl-jpa'
    annotationProcessor "com.querydsl:querydsl-apt:${dependencyManagement.importedProperties['querydsl.version']}:jpa"
    annotationProcessor "jakarta.persistence:jakarta.persistence-api"
    annotationProcessor "jakarta.annotation:jakarta.annotation-api"


참고

https://tecoble.techcourse.co.kr/post/2021-08-08-basic-querydsl/
https://velog.io/@woo0_hooo/Spring-Boot와-QueryDSL-연동하기

https://tecoble.techcourse.co.kr/post/2021-08-08-basic-querydsl/

https://querydsl.com/static/querydsl/3.4.1/reference/ko-KR/html/ch02.html

https://joont92.github.io/jpa/QueryDSL/

https://data-make.tistory.com/615

profile
시간대비효율

0개의 댓글