JPQL equivalent of SQL query using unions and selecting constants

后端 未结 2 1276
南方客
南方客 2020-12-18 13:20

I\'ve written a SQL query that basically selects from a number of tables to determine which ones have rows that were created since a particular date. My SQL looks something

2条回答
  •  执念已碎
    2020-12-18 13:43

    I did a little more searching and found a (seemingly obscure) feature of JPA that serves my purpose perfectly. What I found is that JPA 2 has a type keyword that allows you to limit polymorphic queries to a particular subclass, like so:

    SELECT widget
    FROM BaseWidget widget
    WHERE TYPE(widget) in (WidgetB, WidgetC)
    

    I've found that JPA (or at least Hibernate as a JPA implementation) allows you to use type not only in constraints but also in select lists. This is approximately what my query ended up looking like:

    SELECT DISTINCT TYPE(widget)
    FROM BaseWidget widget
    WHERE widget.creationTimestamp > :cutoff
    

    That query returns a list of Class objects. My original query was selecting string literals because that's closest to what I might have done in SQL. Selecting Class is actually preferable in my case. But if I did prefer to select a constant based on an entity's type, that is the exact scenario that Oracle's documentation uses to illustrate case statements:

    SELECT p.name
    CASE TYPE(p)
      WHEN Student THEN 'kid'
      WHEN Guardian THEN 'adult'
      WHEN Staff THEN 'adult'
      ELSE 'unknown'
    END
    FROM Person p
    

提交回复
热议问题