Question

I'm stuck when rewriting fairly simple pure sql statement to criteria queries. Basically I can simplify my query to

select max(T.value, S.value) from T, S where T.id = S.id

I have tried

CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery();

Root<T> fromT = cq.from(T.class);
Root<S> fromS = cq.from(S.class);

cq.where(cb.equal(fromT.get("id), fromS.get("id"));

cq.select(); //  <---- what to put here.


getEntityManager().createQuery(cq).getResultList();

I found greatest method but it compares horizontally (values from column) and I would like to compare two values from the same row but different column and get one with biggest value.

Only solution which comes to me mind is to get the results and sort them 'manually' but this can influence performance.

Was it helpful?

Solution

You can try the below case statement.

cb.selectCase().
    when(cb.greaterThanOrEqualTo(fromT.get("xValue"), fromS.get("yValue")), fromT.get("xValue")). //-- If T has max value
    otherwise(fromS.get("yValue")); //-- Else, by default select value from S

OTHER TIPS

Can you just use a case statement?

SELECT
  CASE
    WHEN T.value < S.value THEN S.value
    ELSE T.value
  END
FROM
  T, S
WHERE
  T.id = S.id

I would also suggest changing this to an inner join if at all possible:

SELECT
  CASE
    WHEN T.value < S.value THEN S.value
    ELSE T.value
  END
FROM
  T INNER JOIN S
    ON T.id = S.id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top