gpt4 book ai didi

java - 重写 JPA @Embedded 列上的排序行为

转载 作者:行者123 更新时间:2023-12-01 05:20:59 25 4
gpt4 key购买 nike

我有一个实体类,其中有一个嵌入对象:

@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 从数据库中获取 Flights 并在时间列上创建 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 似乎不适合这项工作。有人有什么想法吗?

提前致谢。

最佳答案

我什至不知道您可以通过查询在这样的可嵌入属性上添加订单。但我不会依赖它,只需在您的查询中添加两个订单即可:

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);

关于java - 重写 JPA @Embedded 列上的排序行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10431593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com