2016-01-20 62 views
0

我有4個表。對於這個問題,我將它們命名爲tableA,tableB,tableC,tableD。分離表中按列排序的Hibernate

tableB的看起來就像這樣:ID,名稱,標籤,some_other_parameters

表C看起來就像這樣:ID,密碼,some_other_parameters

提交列: ID, tableA_id, tableB_id, tableC_id , entityVersion

tableD中的列沒有在實體中定義一對多,多對一的關聯。它不能改變。無所謂但爲什麼不能改變。 列的定義如下所示: @Column(name - 「T_tableA_ID」) private long tableAId;

對於tableB和tableC,列定義看起來是一樣的。

排在提出這個樣子插入時:

TABLEA不爲空,tableB的不爲空,表C是空

或:

TABLEA不爲空,tableB的爲空,表C is not null

我想從tableD中獲取列表,按順序排列: tableB rows by label || ''||命名ASC - (標籤可以爲不同的行一樣,名稱是唯一的) ,然後通過asc碼

分類 表C排它甚至有可能這樣做的標準是什麼?

現在我創建了viewD和tableD視圖。當我在tableD中更新或插入行時,我使用表的實體。所以我有兩個實體:view(具有列display_name和我按此列排序)和table(用於插入和更新)。但是這個解決方案對我來說並不完美。我寧願使用標準。

我需要的標準是這樣的:

select * from 
TABLE_D tab_d 
where TABLE_A_ID = 1 --example id 
order by TABLE_B_ID, 
case when TABLE_B_ID is not null then 
(select code from TABLE_B where id = tab_d.TABLE_B_ID) 
else 
(select label || ' ' || name from TABLE_C where id = tab_d.TABLE_C_ID) 
end 

返回排序的數據另一個SQL我需要的方式:

select tab_d.* from 
table_d tab_d 
left join table_b tab_b on tab_b.id = tab_d.t_groups_id 
left join table_c tab_c on tab_c.id = tab_d.t_users_id 
where table_a_id = 10485 
order by tab_d.t_groups_id, tab_b.code, tab_c.name || ' ' || tab_c.surname 

可以創建標準,以第一或第二個SQL語句?

回答

0

您可以擴展org.hibernate.criterion.Order並提供您自己的實現,它爲訂單生成SQL。見the code example

public class OrderBySqlFormula extends Order { 
    private String sqlFormula; 

    /** 
    * Constructor for Order. 
    * @param sqlFormula an SQL formula that will be appended to the resulting SQL query 
    */ 
    protected OrderBySqlFormula(String sqlFormula) { 
     super(sqlFormula, true); 
     this.sqlFormula = sqlFormula; 
    } 

    public String toString() { 
     return sqlFormula; 
    } 

    public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { 
     return sqlFormula; 
    } 

    /** 
    * Custom order 
    * 
    * @param sqlFormula an SQL formula that will be appended to the resulting SQL query 
    * @return Order 
    */ 
    public static Order sqlFormula(String sqlFormula) { 
     return new OrderBySqlFormula(sqlFormula); 
    } 
} 

,然後只用你的訂單

criteria.addOrder(OrderBySqlFormula.sqlFormula("(a + b) desc"));