編輯:我已經完全編輯了這篇文章,以便我的問題的新描述包括所有的細節,而不僅僅是我之前認爲的相關內容。也許這個新的描述將有助於解決我面臨的問題。Projections.count()和Projections.countDistinct()都會導致相同的查詢
我有兩個實體類Customer和CustomerGroup。客戶和客戶羣體之間的關係是ManyToMany。顧客組在Customer類中以下列方式進行註釋。
@Entity
public class Customer {
...
@ManyToMany(mappedBy = "customers", fetch = FetchType.LAZY)
public Set<CustomerGroup> getCustomerGroups() {
...
}
...
public String getUuid() {
return uuid;
}
...
}
在客戶羣類的客戶參考下面的方式被註解
@Entity
public class CustomerGroup {
...
@ManyToMany
public Set<Customer> getCustomers() {
...
}
...
public String getUuid() {
return uuid;
}
...
}
注意,無論是CustomerGroup和Customer類也有一個UUID場。 UUID是一個唯一的字符串(數據模型中不強制唯一性,正如您所看到的,它被處理爲任何其他正常字符串)。
我想要做的是取出所有不屬於任何客戶羣的客戶,或者客戶羣是「有效羣組」。客戶組的有效性由有效的UUID列表定義。
我創建了以下標準查詢
Criteria criteria = getSession().createCriteria(Customer.class);
criteria.setProjection(Projections.countDistinct("uuid"));
criteria = criteria.createCriteria("customerGroups", "groups", Criteria.LEFT_JOIN);
List<String> uuids = getValidUUIDs();
Criterion criterion = Restrictions.isNull("groups.uuid");
if (uuids != null && uuids.size() > 0) {
criterion = Restrictions.or(criterion, Restrictions.in(
"groups.uuid", uuids));
}
criteria.add(criterion);
當執行查詢時,它會導致下面的SQL查詢
select
count(*) as y0_
from
Customer this_
left outer join
CustomerGroup_Customer customergr3_
on this_.id=customergr3_.customers_id
left outer join
CustomerGroup groups1_
on customergr3_.customerGroups_id=groups1_.id
where
groups1_.uuid is null
or groups1_.uuid in (
?, ?
)
查詢正是我想要的,但是有一個例外。由於客戶可以屬於多個CustomerGroups,因此加入CustomerGroup會導致重複的Customer對象。因此count(*)
會給出一個錯誤的值,因爲它只計算有多少結果。我需要獲得大量的獨特客戶,而我期望通過使用Projections.countDistinct("uuid");
投影來實現這一點。出於某種原因,如您所見,投影仍然會導致count(*)
查詢,而不是預期的count(distinct uuid)
。用count("uuid")
替換投影countDistinct
將導致完全相同的查詢。
我做錯了什麼或者這是一個錯誤?
===
「問題」已解決。原因:PEBKAC(鍵盤和椅子之間存在問題)。我在我的代碼中有一個分支,並沒有意識到分支已被執行。該分支使用rowCount()而不是countDistinct()。
。如果你正在使用的標準只有創造了基本查詢事後追加左側手動加入:那就是不要做:) – Fortega 2010-02-23 14:52:00
的方式我已經編輯到包含與我的問題所有代碼的問題。 – 2010-02-24 06:26:44
對於其他有同樣問題的掙扎,看到了這個問題:http://stackoverflow.com/questions/4616607/projections-countdistinct-with-hibernate-produces-unexpected-result – simon 2011-01-07 11:59:22