开发者

Ordering by varying columns in JPQL/Hibernate

开发者 https://www.devze.com 2023-01-25 18:34 出处:网络
I have a table of Sessions. Each session has \"session_start_time\" and \"session_end_time\". While the session is open, the end time is empty. I want to fetch the list of sessions, and order it by th

I have a table of Sessions. Each session has "session_start_time" and "session_end_time". While the session is open, the end time is empty. I want to fetch the list of sessions, and order it by the following logic:

  1. If the session is open (no end time), order by the start time.
  2. If the session is closed, order by the end time.

Something like:

 ORDER BY (session_end_time == null) ? session_start_time : session_end_time

I'm using JPA and JPQL for the queries, and using Hibernate for the execution. What would you recommend?

NOTE: I would rather not add C开发者_开发问答ASE to the SELECT, but instead keep it clean so I get a list of sessions without additional unneeded fields.


ORDER BY nvl(session_end_time, session_start_time)

nvl is an Oracle function. I'm sure ther are functions like that for other DBMS

Found this one for hibernate: nvl in HIBERNATE: How to simulate NVL in HQL

ORDER BY: https://forum.hibernate.org/viewtopic.php?f=25&t=997220&start=0


Does

ORDER BY CASE 
    WHEN session_end_time IS NULL THEN session_start_time 
    ELSE session_end_time 
END 

work in your DBMS? That doesn't add a field.

Otherwise you can calculate it inside a nested query, but don't include it in the final SELECT clause:

SELECT field1, field2 FROM (
    SELECT field1, field2, CASE WHEN session_end_time... END AS dummyfield
) Q
ORDER BY Q.dummyfield
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号