我有一个包含以下各列的表:

@Column(name="CTDESTATUS")
private String status;
@Column (name= "CTDEMESSAGE")
private String message;
@Temporal(TemporalType.TIMESTAMP)
@Column (name = "CTDTDATE")
private Date date;
@Column (name = "CTCDSERVICEID")
private String serviceId;


我需要构建一个查询,该查询返回添加到数据库中的最后n行,并按serviceId分组,其中每一行都是包含以下status之一的较旧的行:

STARTRUNNINGPAUSEDEND_ERROREND_SUCCESS

并按date降序对结果进行排序。
我不熟悉Eclipselink API,我想要这样的东西:

ExpressionBuilder builder = new ExpressionBuilder();
Expression exStatus1 = builder.get("status").equal("START");
Expression exStatus2 = builder.get("status").equal("RUNNING");
Expression exStatus3 = builder.get("status").equal("PAUSED");
Expression exStatus4 = builder.get("status").equal("END_ERROR");
Expression exStatus5 = builder.get("status").equal("END_SUCCESS");
Expression exStatus = (exStatus1).or(exStatus2).or(exStatus3).or(exStatus4).or(exStatus5);
Expression exGroup = builder.get("serviceId").distinct();
Expression exOrder = builder.get("date").descending();
ReadAllQuery query = new ReadAllQuery();
query.setReferenceClass(Notification.class);
query.setSelectionCriteria(exStatus);
query.addDescendingOrdering("date");
query.setMaxRows(n);


有人可以帮我吗?

最佳答案

应该是这样的。我没有在IDE上尝试过它,因此它可能会有一些错误,但是应该可以帮助您入门。

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Notification> cq = criteriaBuilder.createQuery(Notification.class);
Metamodel m = entityManager.getMetamodel();
EntityType<Notification> Notification_ = m.entity(Notification.class);

Root<Notification> root = cq.from(Notification_);

Expression<String> exp1 = criteriaBuilder.upper(root.<String>get("status"));

Predicate predicate1 = criteriaBuilder.like(emp1, "START");
Predicate predicate2 = criteriaBuilder.like(emp1, "PAUSED");
Predicate predicate3 = criteriaBuilder.like(emp1, "RUNNING");
Predicate predicate4 = criteriaBuilder.like(emp1, "END_ERROR");
Predicate predicate5 = criteriaBuilder.like(emp1, "END_SUCCESS");

Predicate predicate = criteriaBuilder.or(predicate1, predicate2, predicate3, predicate4, predicate5)
cq.where(predicate);
cq.orderBy(criteriaBuilder.desc(root.get("date")));

Query query = entityManager.createQuery(cq);
query.setMaxResults(n);
return query.getResultList();

08-26 20:43