2010-10-19 112 views
0

我有以下實體(不準確,但給出了一個總體思路):不同結果的讀取與查詢API的結果與HQL

 
@Entity 
public class WebElement implements Serializable { 
    private static final long serialVersionUID = 1L; 

    @Id 
    @GeneratedValue 
    private Long id; 

    @ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.ALL }) 
    private Set<CoreElement> coreElements; 

    private String agent; 

    // ... omitting const' get/set hashcode equals etc. 
} 
 
public class CoreElement implements Serializable { 
    private static final long serialVersionUID = 1L; 

    @Id 
    @GeneratedValue 
    private Long id; 

    private String value; 
    // ... omitting const' get/set hashcode equals etc. 
} 

我的問題是試圖使用Criteria API來獲取WebElements時與HQL
當執行以下時,我得到一個空的列表。

getCurrentSession().createCriteria(WebElement.class) 
         .createCriteria("coreElements").add(
             Restrictions.eq("value", value)).list(); 

但在執行以下HQL當我得到正確的結果。

select distinct we from WebElement we, in(we.coreElements) core 
            where core.value = :inputValue 

你能幫找到我在做什麼呼叫之間錯誤或有什麼不同?
注意我的選擇是與標準API工作HQLs代替。

回答

0

在你的HQL要創建一個內部聯接導致Hibernate來獲取這些元素

在條件查詢,你可以使用FetchMode.JOIN

調用setFetchMode()由於您的查詢是靜態的,我會建議使用HQL - 這很容易理解,

+0

也嘗試過,取模不改變結果。我用HQL離開了它,但是這個問題仍然讓我感到擔憂。 – Bivas 2010-10-19 15:20:21

+0

告訴我們你的代碼然後... – 2010-10-19 15:45:09

0

您使用的是Restrictions.eq代替Restrictions.in()。由於您使用的HQL。

+0

in()方法是HQL short join join。這兩個調用產生(幾乎)相同的SQL。我改變了Criteria API與'in'一起工作,但得到了同樣的無結果結果。 – Bivas 2010-10-19 14:52:53