[英]Is it possible to use COUNT with a DISTINCT JPA projection?
我正在使用 JPA 不同投影來獲取一些數據:
select distinct o.f1, o.f2, o.f3 from SomeEntity o where ...
這適用於 setFirstResult 和 setMaxResults 頁面數據。
但是我需要計算總行數而不提取所有行數。 我試過:
select count(distinct o.f1, o.f2, o.f3) from SomeEntity o where ...
這不起作用(無論如何使用 EclipseLink)並且 JPA 規范似乎不允許這樣做。 還有其他方法嗎? 我不想編寫 SQL 查詢來執行此操作。
試試這個:
select count(distinct o) from SomeEntity o where ...
如果 EclipseLink 和您的底層數據庫允許子選擇,請嘗試:
select count(*) from (select distinct o.f1, o.f2, o.f3 from SomeEntity o where ... )
這樣您就可以將 JQL 放入計算其總結果大小。
這適用於 hibernate sql 命名查詢。 我很快就會在 JP-QL 查詢上試用它。
雖然這個答案來晚了,但它可能會幫助未來的人。 在您的存儲庫中。 這在我自己的情況下對我有用。
@Query("SELECT DISTINCT COUNT(o.f1, o.f2...) FROM SomeEntity o WHERE....)
希望它可以幫助其他人。
您說您不想編寫 SQL 查詢來執行此操作,但是 JPA QL 和 SQL 之間有什么區別? 如果不想使用getResultList().size()
方法來確定總行數,那么唯一的方法就是使用原生 sql 查詢。
entityManager.createNativeQuery("select count(distinct o.f1, o.f2, o.f3) from SomeEntity o where ...").getSingleResult();
或
entityManager.createQuery("select distinct o.f1, o.f2, o.f3 from SomeEntity o where ...").getResultList().size();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.