简体   繁体   中英

How to convert SQL statement with sub query into HQL

I have a relatively simple SQL query:

SELECT TOP 10 * From Occasion 
WHERE 
(Occasion.StateId = @StateId AND Occasion.EndTime < @EndTime) 
OR 
(
   Occasion.StateId = @StateId 
   AND 
   @StartTime < (SELECT TOP 1 Time FROM StartTime where Occasion.OccasionId = StartTime.OccasionId ORDER BY Time DESC)
)

But I have no idea how to convert this into HQL. I've made a number of attempts but have been unable to get this to work. I receive mostly compile time errors which means my syntax is incorrect. Any help would be greatly appreciated.

Here are the relevant parts of my mapping file:

<id name="Id" column="OccasionId" type="guid">
  <generator class="guid" />
</id>

<bag name="StartTimeCollection" lazy="false" access="nosetter.camelcase-underscore" table="StartTime">
  <key column="OccasionId" />
  <element type="datetime2">
    <column sql-type="datetime2(7)" not-null="true" name="Time" />
  </element>
</bag>

<property name="EndTime" type="datetime2">
  <column name="EndTime" sql-type="datetime2(7)" not-null="false" />
</property>

<many-to-one not-null="true" lazy="false" fetch="join" name="_state" column="StateId" access="field" />

<property name="Status" formula="StateId" access="readonly" insert="false" update="false" />

<id name="Id" column="OccasionStateId">
  <generator class="native" />
</id>

<discriminator column="Name" type="string">
  <column name="Name" sql-type="nvarchar(256)" />
</discriminator>

<subclass name="PendingState" discriminator-value="Pending" />
<subclass name="StartedState" discriminator-value="Started" />
<subclass name="EndedState" discriminator-value="Ended" />

I don't know your class model, so I have to guess.

Assuming that there is a onw-to-many relation Occasion to StartTime (which is only a list of primitive values of time):

From Occasion o
WHERE 
  (o.StateId = :StateId 
    AND o.EndTime < :EndTime)
  OR 
  (
     o.StateId = :StateId 
     AND :StartTime < max(elements(o.StartTimes))
  )

(TOP 10 is done with .SetMaxresults(10) .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM