2014-08-28 69 views
2

我有兩個postgreSQL表首選項,date_etl和preference_date_etl存儲它們的映射。休眠在同一個表上使用多個聯接

preference_date_etl的Hibernate映射:

<hibernate-mapping> 

    <class name="com..bla.bla.PreferenceDateETL" 
     table="preference_date_etl"> 
     <id name="id" column="id" unsaved-value="null"> 
      <generator class="sequence"> 
       <param name="sequence"> 
      <![CDATA[preference_date_etl_id_seq]]> 
       </param> 
      </generator> 
     </id> 

     ...things.... 
    </class> 
</hibernate-mapping> 

所以,現在當我執行一個HQL喜歡:

select distinct pd.preference from PreferenceDateETL pd where pd.corporation.id=:corporationId and pd.preference.employee.deleted=false and pd.deleted=false and pd.preference.deleted=false and pd.dateETL.localDate>=:startDM and pd.dateETL.localDate<=:endDM and pd.preference.approvalStatus!=:approvalStatus order by pd.preference.dateCreated 

轉換爲SQL:

select 
     distinct preference1_.id as id1_76_, 
     ....things... 
    from 
     preference_date_etl preference0_ 
    inner join 
     preference preference1_ 
      on preference0_.preference_id=preference1_.id cross 
    join 
     preference preference2_ cross 
    join 
     employee employee3_ cross 
    join 
     date_etl dateetl5_ 
    where 
     ...things... 
    order by 
     preference2_.date_created 

問題:preference2_.date_created在ORDER BY子句不在選擇列表中,因此例外SELECT DISTINCT, ORDER BY expressions must appear in select list

問題:爲什麼在同一個表上使用兩個連接INNER AND CROSS來休眠。如果在ORDER BY列表中有preference1_.date_created那麼一切都會很好。想法?

+0

只是要清楚 - 這是偏好和date_etl之間的多對多關係?不是一對一的? – Hedley 2014-08-28 17:08:22

回答

0

您可以重構此查詢以避免使用distinct關鍵字,因此可以毫無問題地爲您的結果排序。爲此,請將PreferenceDateETL對象的條件設置爲子查詢,然後檢索鏈接到子查詢中PreferenceDateETL對象的首選項對象組中的所有首選對象。這裏是HQL:

from Preference p where p in 
    (select pd.preference from PreferenceDateETL pd 
    where pd.corporation.id=:corporationId 
    and pd.deleted=false 
    and pd.dateETL.localDate>=:startDM 
    and pd.dateETL.localDate<=:endDM) 
and p.employee.deleted=false 
and p.deleted=false 
and p.approvalStatus != :approvalStatus 
order by p.dateCreated