2012-02-28 26 views
2

例如,我有這樣的查詢與許多一對多WHERE子句

<class name="my.test.model.Product" table="PRODUCT"> 
    ... 
      <set name="retailers" table="product_shop" lazy="false"> 
       <key column="PRODUCT_ID" /> 
       <many-to-many column="SHOP_ID" class="my.test.model.Shop" /> 
      </set> 
    ... 
    </class> 

映射文件現在我想查詢某家商店A的產品中集(連接表)想到這樣的事情:

String searchHql = "select p from Product p inner join p.retailers retailing where p.retailers.shop_id = :shopId"; 

     @SuppressWarnings("unchecked") 
     List<Product> productList = sessionFactory.getCurrentSession().createQuery(searchHql).setInteger("shopId", shopId).list(); 

但它不會工作。返回的錯誤是:

無法解析屬性:shop_id:my.test.model.Shop。我搜索了很多,但仍然沒有找到正確的方法來訪問hql中的「多對多」子集。這可能嗎?或者我需要將Product_Shop表映射到模型類?

UPDATE:因爲看起來沒有其他辦法,我最終將Product_Shop映射到類中。

回答

3

你應該使用你給的加盟實體wgere子句中的別名:

select p from Product p inner join p.retailers retailing 
where retailing.shop_id = :shopId 

旁註:你應該尊重的Java命名約定:shopId而非shop_id

+0

不幸的是,shop_id是列名。我的「Shop」模型的ID爲「id」(與Product相同),所以當我使用「retailing.id」時,它使用「Product」的「id」代替。 – 2012-02-29 07:24:27

+1

HQL查詢從不使用表名和列名,但始終使用實體名和字段/屬性名。 – 2012-02-29 08:01:42

+0

是的,但是這次連接表中的2個屬性名稱之間存在重複。 – 2012-02-29 09:09:23