카테고리 없음
[SQL] QueryDSL
321
2021. 6. 16. 21:00
http://www.querydsl.com/static/querydsl/4.0.1/reference/ko-KR/html_single/
Querydsl - 레퍼런스 문서
본 절에서는 SQL 모듈의 쿼라 타입 생성과 쿼리 기능을 설명한다. com.querydsl.sql.Configuration 클래스를 이용해서 설정하며, Configuration 클래스는 생성자 인자로 Querydsl SQL Dialect를 취한다. 예를 들어, H2
www.querydsl.com
dependencies
- querydsl-apt
- querydsl-jpa
- slf4j-log4j12
apt plugin
<project>
<build>
<plugins>
...
<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>
...
</plugins>
</build>
</project>
hibernate를 한번 더 씌우고 싶으면 레퍼런스 2.1.1을 참고하면 됨
쿼리 타입 사용하기
@Entity
public class Customer {
private String firstName;
private String lastName;
}
이러한 엔티티가 있다고 한다면
Querydsl을 사용해서 QCustomer라는 쿼리타입을 생성할 수 있다.
QCustomer customer = QCustomer.customer;
//혹은
QCustomer customer = new QCustomer("myCustomer");
쿼리
- 인스턴스 받아올 때
//걍 JPA
JPAQuery query = new JPAQuery(entityManager);
//hibernate사용한것
HibernateQuery query = new HibernateQuery(session);
- 조회하고 싶을 때(firstName이 OH인 customer를 조회한다면)
QCustomer customer = QCustomer.customer;
JPAQuery query = new JPAQuery(entityManager);
Customer bob = query.from(customer)
.where(customer.firstName.eq("OH"))
.uniqueResult(customer);
- 여러 소스로부터 쿼리를 만들고 싶을 때(customer, company에서 받아와서 만든다면)
QCustomer customer = QCustomer.customer;
QCompany company = QCompany.company;
query.from(customer, company);
//방법1
query.from(customer)
.where(customer.firstName.eq("Bob"), customer.lastName.eq("Wilson"));
//방법2
query.from(customer)
.where(customer.firstName.eq("Bob").and(customer.lastName.eq("Wilson")));
위 방법에서 sql문은
select * from customer where customer.firstname="Bob" and customer.lastName="Wilson"
그래서 이러한 sql문을 추가할 때 쿼리 dsl문법은 매서드(찾는 값)를 이용하면 된다.
- from - ~에서
- innerJoin, join, leftJoin, rightJoin, on - 조인
- where - 조건
- groupBy - 그룹
- having - groupBy조건
- orderBy - 정렬
- limit-최대결과개수, offset-결과의 시작행, restrict=limit+offset
이러한 메서드 뒤에 괄호 붙여서 쓰면 됨
예시
- sql문 ( select * 를 빼면 jpql쿼리문도 될 수 있다.
select * from Cat as cat
left join cat.kittens as kitten
on kitten.bodyWeight > 10.0
- 쿼리 dsl문
query.from(cat)
.leftJoin(cat.kittens, kitten)
.on(kitten.bodyWeight.gt(10.0))
.list(cat);