【问题标题】:Query with the many-to-many set (joined table) in the WHERE clause在 WHERE 子句中使用多对多集合(连接表)进行查询
【发布时间】:2012-03-17 16:19:38
【问题描述】:

例如,我有这样的映射文件

   <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(); 

但这行不通。返回的错误是:

无法解析属性:my.test.model.Shop 的 shop_id。我已经搜索了很多,但仍然没有找到访问 hql 中“多对多”子集的正确方法。这可能吗?或者我需要将 Product_Shop 表映射到模型类?

更新:似乎没有其他办法,我最终将 Product_Shop 映射到一个类中。

【问题讨论】:

    标签: java hibernate many-to-many hql


    【解决方案1】:

    您应该使用您在 wgere 子句中分配给连接实体的别名:

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

    附注:您应该尊重 Java 命名约定:shopId 而不是 shop_id

    【讨论】:

    • 不幸的是,shop_id 是列名。我的模型“Shop”的 ID 为“id”(与 Product 相同),所以当我使用“retailing.id”时,它会使用“Product”的“id”。
    • HQL 查询从不使用表名和列名,但始终使用实体和字段/属性名称。
    • 是的,但这次在连接表中的 2 个属性名称之间存在重复。
    猜你喜欢
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 2015-11-10
    • 2018-03-27
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多