2012-05-03 61 views
1

我有一個具有在其內的嵌入對象實體類:重寫排序行爲

@Entity 
public class Flight implements Serializable { 

    /// .... other attributes 
    @Embedded 
    @AttributeOverrides({ 
     @AttributeOverride(name = "value", column = 
     @Column(name = "FLIGHT_TIME")), 
     @AttributeOverride(name = "dataState", column = 
     @Column(name = "FLIGHT_TIME_TYPE", length = 20)) 
    }) 
    private DateDataStateValue flightDate; 
} 

的DateDataStateValue如下:

@Embeddable 
public class DateDataStateValue implements DataStateValue<Date>, Serializable { 

    private static final long serialVersionUID = 1L; 

    @Column(name = "DATASTATE") 
    @Enumerated(value = EnumType.STRING) 
    private final DataState dataState; 

    @Column(name = "DATAVALUE") 
    @Temporal(TemporalType.TIMESTAMP) 
    private final Date value; 
} 

當執行讀取航班的從數據庫中使用CriteriaQuery並在時間列上創建Order對象:

Path<Flight> propertyPath = queryRoot.get("flightDate"); 
Order order = isAscending() ? criteriaBuilder.asc(propertyPath) : criteriaBuilder.desc(propertyPath); 

排序不是我想要的。舉例來說,如果飛行表具有以下值:

Flight 1 | ESTIMATED | 1 Jan 2012 
Flight 2 | ESTIMATED | 1 Jan 2011 
Flight 3 | ACTUAL | 1 Jan 2010 
Flight 4 | ESTIMATED | 1 Jan 2009 

升序排序的結果將是:

Flight 3 | ACTUAL | 1 Jan 2010 
Flight 4 | ESTIMATED | 1 Jan 2009 
Flight 2 | ESTIMATED | 1 Jan 2011 
Flight 1 | ESTIMATED | 1 Jan 2012 

看來,一個@Embedded列的默認排序是使用這些元素按照它們在類中被命名的順序進行自然排序。首先是DATASTATE,然後是DATAVALUE。

我希望做的是,每當那種屬性是flightDate,順序是先日期,那麼狀態,即:

Flight 4 | ESTIMATED | 1 Jan 2009 
Flight 3 | ACTUAL | 1 Jan 2010 
Flight 2 | ESTIMATED | 1 Jan 2011 
Flight 1 | ESTIMATED | 1 Jan 2012 

使得DateDataStateValue可比性並不影響它,並@ orderColumn/@ OrderBy似乎不適合這項工作。有沒有人有任何想法?

在此先感謝。

回答

0

我甚至不知道你可以通過查詢在這樣一個可嵌入的屬性上添加一個訂單。但我不會依賴於它,只需添加兩個命令來查詢:

Path<Flight> statePath = queryRoot.get("flightDate.dateState"); // or queryRoot.get("flightDate").get("dateState"): to be tested 
Path<Flight> valuePath = queryRoot.get("flightDate.value"); 
Order[] orders; 
if (isAscending()) { 
    orders = new Order[] {criteriaBuilder.asc(valuePath), criteriaBuilder.asc(statePath) }; 
} 
else { 
    orders = new Order[] {criteriaBuilder.desc(valuePath), criteriaBuilder.desc(statePath) 
} 

query.orderBy(orders); 
+0

感謝的自然排序,看起來我可能需要做這樣的事情。 – fancyplants

0

"flightDate.value ASC, flightDate.dataState ASC"也許,因爲所有你定義爲「flightDate」,這意味着該對象