Gorm/Hibernate와 함께 열망하는 쿼리
문제
Grails 앱에는 다음 도메인 개체가 있습니다
class ProductType {
String name
static hasMany = [attributes: Attribute]
}
class Attribute {
String name
static belongsTo = [productType: ProductType]
}
내 DB에는 7이 있습니다 ProductType
S와 그 각각에는 3이 있습니다 Attribute
에스. 쿼리를 실행하면 :
def results = ProductType.withCriteria {
fetchMode("attributes", org.hibernate.FetchMode.EAGER)
}
나는 7 개의 인스턴스를 기대한다 ProductType
반환되지만 실제로는 21 (7 x 3)을 얻습니다. 위의 것과 동등한 SQL 쿼리를 실행하려면 결과 세트에 21 행이있을 것임을 이해합니다.
prod1 | attr1
prod1 | attr2
prod1 | attr3
..... | .....
..... | .....
prod7 | attr1
prod7 | attr2
prod7 | attr3
-------------
Total 21
그러나 나는 최대 절전 모드/gorm을 통해이 결과를 검색 할 때 다음과 같은 것을 얻어야한다고 생각했습니다.
prod1 | attr1, attr2, attr3
..... | ...................
..... | ...................
prod7 | attr1, attr2, attr3
---------------------------
Total 7
덧붙여서 위의 쿼리에서 열성적인로드를 제거하면 7 ProductType
예상대로. 내가 무엇을 놓치고 있습니까?
해결책
당신은 이것을 읽어야합니다 FAQ : Hibernate는 컬렉션에 대한 외부 결합 페치가 활성화 된 쿼리에 대한 뚜렷한 결과를 반환하지 않습니다 (고유 한 키워드를 사용하더라도)?
열심히 로딩을 지정할 때, 결과 세트에는 7*3 행이 포함되지만 실제로는 메모리에 7 개의 제품 유형 객체 만 있습니다 (각각 2 개의 추가 참조).
원하는 작업을 수행하려면 추가 할 수 있습니다 (기본 SQL 쿼리가 변경되지 않았 음을 알고 있어야합니다).
SetResultTransformer(new DistinctRootEntityResultTransformer())
def results = ProductType.withCriteria {
fetchMode("attributes", org.hibernate.FetchMode.EAGER)
SetResultTransformer(new DistinctRootEntityResultTransformer())
}
제휴하지 않습니다 StackOverflow