문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top