Question

I have a table that contains the following columns:

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

I need to build a query that returns the last n rows added to database, grouped by serviceId, where each row is the older one that contains one of the following status:

START or RUNNING or PAUSED or END_ERROR or END_SUCCESS

And sort the result by date descending. I'm not familiar with the Eclipselink API, and I want something like that:

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

Someone can help me?

Was it helpful?

Solution

It should be something like this. I haven't tried it on the IDE so it may have some errors, but should get you started.

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top