2011-10-15 48 views
0

我有以下HQL查詢:HQL右外連接與返回的部分結果InheritanceType.SINGLE_TABLE

entityManager.createQuery("Select customer FROM VisitEntry 
visitEntry RIGHT OUTER JOIN visitEntry.customer customer 
GROUP BY customer ORDER BY max(visitEntry.date) desc").getResultList(); 

這是我的目標:

@Inheritance(strategy=InheritanceType.SINGLE_TABLE) 
public class LogEntry implements Comparable<LogEntry> { 
...  
    @Column(name="LOGENTRY_DATE") 
    public Calendar getDate() { 
     return date; 
    } 

    public void setDate(Calendar calendar) { 
     this.date = calendar; 
    } 
    @Column(name="LOGENTRY_TEXT") 
    public String getText() { 
     return text; 
    } 
    public void setText(String text) { 
     this.text = text; 
    } 

    @OneToOne 
    public Customer getCustomer() { 
     return customer; 
    } 
    public void setCustomer(Customer member) { 
     this.customer = member; 
    } 

... 
} 

和客戶:

@Entity 
@Table(name="CUSTOMER") 
public class Customer { 

    private Integer id; 
    @Id 
    @GeneratedValue 
    @Column(name="ID") 
    public Integer getId() { 
     return id; 
    } 
    public void setId(Integer id) { 
     this.id = id; 
    } 

} 

這翻譯成以下SQL:

select * from LOGENTRY visitentry0_ right outer join 
CUSTOMER customer1_ on visitentry0_.customer_ID=customer1_.ID 
where visitentry0_.DTYPE in ('VisitEntry', 'TimeVisitEntry', 
'PpvVisitEntry', 'InactiveVisitEntry') group by customer1_.ID 
order by max(visitentry0_.LOGENTRY_DATE) desc 

我這樣做時,我直接在數據庫上使用SQL查詢得到的所有結果:

SELECT CUSTOMER.MEMBER_FIRSTNAME, MAX(LOGENTRY_DATE) FROM LOGENTRY 
RIGHT JOIN CUSTOMER ON LOGENTRY.CUSTOMER_ID = CUSTOMER.ID 
GROUP BY CUSTOMER.ID ORDER BY MAX(LOGENTRY_DATE) DESC 

因此,即使這些查詢幾乎是一樣的只有後者讓我回到正確的結果。第一個查詢僅返回具有關聯LOGENTRY的客戶,第二個查詢返回所有客戶(即使他們沒有與其關聯的LOGENTRY)。通過HQL查詢(不正確)返回

Matthias 2011-09-22 22:31:38 
Christophe 2011-09-22 22:24:03 
Patrick Leander 2011-09-21 20:47:49 
Thomas 2011-09-21 20:19:09 
Ricky (null) 
Glenn Gunther (null) 

結果:

結果通過SQL查詢(正確)返回

Matthias 2011-09-22 22:31:38 
Christophe 2011-09-22 22:24:03 
Patrick Leander 2011-09-21 20:47:49 
Thomas 2011-09-21 20:19:09 

回答

0

不能相信我錯過了這一點,但這個問題實際上是在從HQL查詢生成的SQL查詢本條款:

where visitentry0_.DTYPE in ('VisitEntry', 'TimeVisitEntry', 
'PpvVisitEntry', 'InactiveVisitEntry') 

問題是,我想查詢返回客戶的結果沒有任何訪問條目,但查詢中的該子句(由休眠生成)不會返回類型爲NULL的visitentrys。

這是我冬眠應該產生對我來說,返回所有結果的SQL:

where visitentry0_.DTYPE in ('VisitEntry', 'TimeVisitEntry', 
    'PpvVisitEntry', 'InactiveVisitEntry') OR visitentry0_ IS NULL 

對我來說,這似乎是在Hibernate中的一個缺陷,因爲這阻止了左或右聯接返回正確的結果。

+0

有趣的是,當我將LogEntry的InheritanceType更改爲InheritanceType.TABLE_PER_CLASS時,它起作用。 –

0

不同的結果,我們應有這樣的事實:在SQL查詢你正在使用「正確的連接」,並且在HSQL上使用「正確的外部連接」時,適當地改變以獲得期望的結果。

+0

不起作用,如果我在HQL中編寫RIGHT JOIN,它只是將它翻譯爲RIGHT OUTER JOIN in SQL –