2016-10-25 75 views
0

當我使用hibernate的條件執行查詢時遇到問題。生成的SQL很簡單:錯誤:列「this_.created_time」必須出現在GROUP BY子句中或用於聚合函數

/* criteria query */ 
select 
    count(*) as y0_ 
from 
    cx_vss_video this_ 
where 
    this_.uploader_id=? 
order by 
    this_.created_time asc 

它抱怨錯誤:

Caused by: org.postgresql.util.PSQLException: ERROR: column "this_.created_time" must appear in the GROUP BY clause or be used in an aggregate function 
    Position: 105 
     at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2157) 

有一個存在samilar問題here。但其答案似乎非常複雜,並且不合理。那麼還有其他解決方案

我的實體類:

@Entity 
@Table(name = "cx_vss_video") 
public class Video { 

    public enum TranscodingStatus { 
     NOT_START, TRANSCODING, SUCCESS, ERROR, CANCELED; 
    } 

    @Id 
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "cx_vss_video_seq") 
    @SequenceGenerator(name = "cx_vss_video_seq", sequenceName = "cx_vss_video_seq") 
    private Long id; 

    @Column(name = "uploader_name", nullable = false) 
    private String uploaderName; 

    @Column(name = "file_name") 
    @NaturalId 
    private String fileName; 

    @Column(name = "created_time") 
    private Date createdTime = new Date(); 

    @Column(name = "transcoding_status") 
    @Enumerated(EnumType.STRING) 
    private TranscodingStatus transcodingStatus = TranscodingStatus.TRANSCODING; 
} 

我可以file_name normaly秩序,而且當created_time下令沒有運氣。我很困惑問題出現在哪裏?當我使用H2時,問題也會出現。

編輯 我終於通過刪除命令參數解決了問題,它現在可以工作。

CriteriaImpl criteriaImpl = criteria instanceof CriteriaImpl ? (CriteriaImpl) criteria : null; 
    if (criteriaImpl != null) { 
    Iterator<OrderEntry> it = criteriaImpl.iterateOrderings(); 
    while (it.hasNext()) { 
     it.next(); 
     it.remove(); 
    } 
    criteria.setProjection(Projections.rowCount()); 
    totalResults = (long) criteria.uniqueResult(); 
    } 

回答

0

您需要查詢的聚合函數。因此,它應該是這樣的:

select count(*) as y0_ 
from cx_vss_video this_ 
where this_.uploader_id = ? 
group by ?? 
order by max(this_.created_time) asc; 

也就是說,你需要一個group by並修復order by

爲什麼?那麼,你的原始查詢 - 沒有group by - 是一個返回一行的聚合查詢。用一行命令結果集沒有意義。所以,我假設你想要聚合的東西,因此??。然後,您可以通過聚合列或聚合函數進行排序。

相關問題