开发者

Different results fetching results with query api vs. hql

I have the following entity (not exact but gives a general idea):

@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 has开发者_Go百科hcode 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.
}

My problem is when trying to fetch WebElements using the Criteria API vs. HQL

When executing the following I get an empty list.

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

But when executing the following HQL I get the correct result.

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

Can you help finding what am I doing wrong or different between those calls?

(NOTE My preference is to work with the Criteria API instead of HQLs.


In your HQL you are creating an inner join which causes Hibernate to fetch the elements.

In the Criteria Query you can use setFetchMode() using FetchMode.JOIN

Since your query is static, I would recommend using HQL - it's easier to understand.


You are using a Restrictions.eq instead of Restrictions.in()..as you are using the HQL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜