Eclipselink Expression用一些条件检索最后N行

时间:2012-05-23 21:38:11

标签: java sql eclipselink expressionbuilder

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

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

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

它应该是这样的。我没有在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();