회사에서 중복된 엔티티들을 조회하여 각 entity 의 counting 을 하는 작업을 하려고 했습니다.
그런데 엔티티들이 다 중복이 제거돼서 리턴됐다?!
User와 Record 엔티티가 있습니다. 1:N 관계입니다.
User가 Record 에 저장된 것만큼? User를 조회하고 싶습니다.
# querydsl
fun findUsersEntity(): List<UserEntity> {
return from(QUserEntity.userEntity)
.leftjoin(QRecordEntity.recordEntity)
.on(QUserEntity.userEntity.id.eq(QRecordEntity.recordEntity.fkId))
.fetch()
}
# sql
select
ue1_0.id,
ue1_0.name
from
user ue1_0
left join
record re1_0
on ue1_0.id=re1_0.fk_id;
api 응답
sql 리턴
기대했던 응답값은 sql 값과 같습니다. 같은 쿼리이지만 왜 api 응답과 쿼리의 결과는 다른걸까요?
org.hibernate.jpa.QueryHints.HINT_PASS_DISTINCT_THROUGH 옵션을 false 로 주면 SQL distinct 쿼리가 발생하지 않고 하이버네이트가 어플리케이션에서 중복제거를 해줍니다.
org.hibernate.sql.results.spi.ListResultsConsumer<R>

org.hibernate.query.sqm.internal.ConcreteSqmSelectQueryPlan<R>
UniqueSemantic 값이 세팅됩니다. 이 값은 SQM 이 판단하기 때문에 제가 옵션을 세팅할 수 없었습니다.
SQM 이란? Semantic Query Model 로 하이버네이트 6부터 도입됐습니다.
It is the new entity query parser that addresses both JPQL and Criteria API.
https://in.relation.to/2016/08/04/introducing-distinct-pass-through-query-hint/
https://docs.jboss.org/hibernate/orm/6.0/migration-guide/migration-guide.html#query-sqm-distinct