Tech/JPA

Tech/JPA

QueryDSL 5.0 - fetchResults(), fetchCount() Deprecated

🔎 deprecated 된 이유 fetchResults()와 fetchCount()는 개발자가 작성한 select 쿼리를 기반으로 count 용 쿼리를 내부에서 만들어서 실행한다. 하지만 이게 단순한 쿼리에서는 잘 동작하지만, 복잡한 쿼리에서는 제대로 동작하지 않는다. 따라서 count 쿼리가 필요하면 별도로 작성해야 한다. 💻 count 쿼리 예제 List content = queryFactory .selectFrom(item) .where(regDtsAfter(itemSearchDto.getSearchDateType()), searchSellStatusEq(itemSearchDto.getSearchSellStatus()), searchByLike(itemSearchDto.getSearchBy(), i..

Tech/JPA

QueryDSL에서 fetchResults()가 deprecated된 이유

🔎 deprecated된 이유 queryDsl의 fetchResult의 경우 count를 하기위해선 count용 쿼리를 만들어서 실행해야 하는데, 카운트를 하려는 select 쿼리를 기반으로 count 쿼리를 만들어 실행한다. 단순한 쿼리에서는 잘 동작하는데, 복잡한 쿼리(다중그룹 쿼리)에서는 잘 작동하지 않는다. groupby having 절을 사용하는 등의 복잡한 쿼리 문에서 예외가 발생한다. 모든 dialect(방언) count 쿼리가 유효하지는 않다. 📌 결론 fetchResult() 대신에 fetch()를 사용하고, count 쿼리는 별도로 날려준다. 인용 https://velog.io/@nestour95/QueryDsl-fetchResults%EA%B0%80-deprecated-%EB%90%9..

Tech/JPA

QueryDSL의 BooleanExpression

✍️ 정의 QueryDSL에서는 BooleanExpression이라는 where절에서 사용할 수 있는 값을 지원한다. BooleanExpression을 반환하는 메서드를 만들고, 해당 조건들을 다른 쿼리를 생성할 때 사용할 수 있기 때문에 중복 코드를 줄일 수 있다는 장점이 있다. ( 코드의 재사용 ) 🔎 사용법 private BooleanExpression usernameEq(String username) { return StringUtils.hasText(username) ? member.username.eq(username) : null; } private BooleanExpression teamNameEq(String teamName) { return StringUtils.hasText(teamN..

Tech/JPA

Spring Data Jpa 사용자 정의 리포지토리 사용법

QueryDSL과 Spring Data Jpa 를 함께 사용하기 위해서는 사용자 정의 리포지토리를 정의해야 한다. 단계 사용자 정의 인터페이스 작성 - ItemRepositoryCustom 사용자 정의 인터페이스 구현 - ItemRepositoryCustomImpl Spring Data Jpa 리포지토리에서 사용자 정의 인터페이스 상속

Tech/JPA

Auditing을 이용한 엔티티 공통 속성 공통화

Auditing 기능을 활용한 데이터 추적하기 /** *등록자와 수정자를 처리해주는 AuditorAware 를 빈으로 등록한다. */ @Bean public AuditorAware auditorProvider() { return new AuditorAware() { @Override public Optional getCurrentAuditor() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String userId = ""; if (authentication != null) { // 현재 로그인한 사용자의 정보를 조회하여 사용자의 이름을 등록자와 수정자로 지정한다. userId = auth..

Tech/JPA

지연로딩 vs 즉시로딩

즉시로딩 적용시 쿼리 엔티티 하나를 조회했을 뿐인데 order_item 테이블과 item, orders, member 테이블을 조인해서 한꺼번에 가져온다. select o1_0.order_item_id, o1_0.count, o1_0.created_time, i1_0.item_id, i1_0.created_time, i1_0.item_detail, i1_0.item_name, i1_0.item_sell_status, i1_0.price, i1_0.stock_quantity, i1_0.update_time, o2_0.order_id, o2_0.created_time, m1_0.member_id, m1_0.address, m1_0.email, m1_0.password, m1_0.role, m1_0.usern..

Tech/JPA

QueryDsl 사용 및 도출되는 쿼리문 예제

간단한 상품 조회 테스트 코드 @Test @DisplayName("Querydsl 조회 테스트1") void queryDslTest() { JPAQueryFactory queryFactory = new JPAQueryFactory(em); JPAQuery query = queryFactory .selectFrom(item) .where(item.itemSellStatus.eq(ItemSellStatus.SELL)) .where(item.itemDetail.like("%" + "테스트 상품 상세 설명" + "%")) .orderBy(item.price.desc()); List items = query.fetch(); for (Item item1 : items) { System.out.println("ite..

Tech/JPA

QueryDSL gradle, maven 설정 (스프링 부트 3.X 이상)

gradle 설정 queryDSL 은 버전별로 설정이 자주바뀐다. 이에 맞춰 필자는 구글링하여 최적의 해를 정리해보았다. 스프링 부트 2.X 버전에서와 3.X 버전에서의 build.gradle 설정 방법은 다르다. 스프링 부트 2.X 버전 설정 plugins { id 'org.springframework.boot' version '2.2.2.RELEASE' id 'io.spring.dependency-management' version '1.0.8.RELEASE' //querydsl 추가 id "com.ewerk.gradle.plugins.querydsl" version "1.0.10" id 'java' } group = 'study' version = '0.0.1-SNAPSHOT' sourceCompa..

Tech/JPA

쿼리 메서드 Sample 및 JPQL snippet

Keyword Sample JPQL And findByLastnameAndFirstname Or findByLastnameOrFirstname Is, Equals findByFirstname findByFirstnameIs findByFirstnameEquals where x.firstname = ?1 Between findByStartDateBetween LessThan findByAgeLessThan LessThanEqual findByAgeLessThanEqual GreaterThan findByAgeGreaterThan GreaterThanEqual findByAgeGreaterThanEqual After findByStartDateAfter where x.startDate > ?1 Before ..

Tech/JPA

QueryDSL 라이브러리

plugins { id 'java' id 'org.springframework.boot' version '3.0.5' id 'io.spring.dependency-management' version '1.1.0' //id "com.ewerk.gradle.plugins.querydsl" version "1.0.10" // querydsl 관련 명령어를 gradle 탭에 생성해준다. //id 'java' } group = 'study' version = '0.0.1-SNAPSHOT' sourceCompatibility = '17' configurations { compileOnly { extendsFrom annotationProcessor } } repositories { mavenCentral() } d..

kimjingyu
'Tech/JPA' 카테고리의 글 목록