끄적끄적
[jpa] querydsl 사용하기 본문
- pom.xml
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>4.1.4</version>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>4.1.4</version>
<scope>provided</scope>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<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>
QClass들을 생성하기 위해서 "mvn package" 실행(인텔리제이는 ctr 두번 입력후 커맨드창에 입력)
-@Configuration
@Configuration
public class QuerydslConfig {
@PersistenceContext
private EntityManager entityManager;
@Bean
public JPAQueryFactory jpaQueryFactory(){
return new JPAQueryFactory(entityManager);
}
}
- Querydsl Repository 생성
public interface CommentRepositoryCustom {
List<Comment> getCommentList(Board board);
Optional<Comment> getChildComment(Board board, Long group, Long commentId);
List<Comment> getLikedCommentList(Board board, Account account);
}
@RequiredArgsConstructor
public class CommentRepositoryCustomImpl implements CommentRepositoryCustom {
private final JPAQueryFactory queryFactory;
@Override
public List<Comment> getCommentList(Board board) {
return queryFactory
.selectFrom(comment)
.where(comment.board.eq(board))
.orderBy(comment.group.asc(),comment.regDate.asc())
.fetch();
}
@Override
public Optional<Comment> getChildComment(Board board, Long group, Long commentId) {
return Optional.ofNullable(
queryFactory
.selectFrom(comment)
.where(comment.board.eq(board),comment.group.eq(group),comment.commentId.gt(commentId))
.orderBy(comment.regDate.asc())
.fetchFirst());
}
@Override
public List<Comment> getLikedCommentList(Board board, Account account) {
return queryFactory
.selectFrom(comment)
.where(comment.board.eq(board))
.join(likeComment).on(likeComment.comment.commentId.eq(comment.commentId))
.where(likeComment.account.eq(account))
.fetch();
}
}
- sql문을 작성하는 감각으로 IDE를 자동완성과 함께 사용하면 큰 어려움없이 원하는 쿼리 작성 가능
- 참고 : https://joont92.github.io/jpa/QueryDSL/
- Repository 통합하기
public interface CommentRepository extends JpaRepository<Comment,Long>,CommentRepositoryCustom {
}
- Querydsl Repository를 구현하는 구현체는 반드시 xxxxImpl 이라는 명칭으로 끝나는 명명규칙을 반드시 지켜야함
gradle
'개발' 카테고리의 다른 글
[spring] filter에서 예외응답하기 (0) | 2020.03.09 |
---|---|
[jpa] @Entity에 default 값을 설정하기 (0) | 2020.03.09 |
[spring] ControllerAdvice로 예외처리하기(+ 메세지 국제화) (0) | 2020.03.08 |
[java] localdatetime에서 milliseconds얻기 (0) | 2020.03.07 |
[정규식] 정규표현식이 탐색을 탐욕적으로 할 때 (0) | 2020.03.06 |
Comments