【问题标题】:hibernate many-to-many休眠多对多
【发布时间】:2009-11-04 07:48:54
【问题描述】:

我有三个表和 2 个 JPA 模型类:

Unit
------------
id [PK]    - Integer
code       - String
unitGroups - List<UnitGroup>


UnitGroup
------------
id [PK]    - Integer
ugKey      - String
units      - List<Unit>

units 和 unitGroups 之间有多对多的关系。 简要地说,我想编写一个 HQL 查询来获取以下 sql 的输出:

SELECT u.* 
FROM units u, unit_groups ug, unit_group_pairs ugp 
WHERE ugp.UnitID = u.ID 
AND ugp.UnitGroupID = ug.ID 
AND ug.UGKey = 'amount' AND u.ID = 10

【问题讨论】:

    标签: java sql hibernate hql


    【解决方案1】:

    我希望这会奏效,但不确定。请不要否定:)。我自己没有试过这个。只是想出这个,所以它可能会帮助你。干杯。

    from Unit as units 
    inner join fetch units.unitGroups grp
    inner join fetch grp.units
    where grp.ugKey = 'amount' and units.id = 10
    

    【讨论】:

    • 谢谢,但我建立了多对多关联。我的问题是关于 hql。
    • 我收到了这个错误; org.hibernate.loader.MultipleBagFetchException:不能同时获取多个包
    • 我找到了这样的解决方案:select (select u.id from Unit u where u.id = 10) from UnitGroup ug where ug.ugKey = 'amount'
    • 我注意到这不是一个解决方案 :) 它也适用于非“数量”的情况。
    【解决方案2】:

    最后:

    select u from Unit u left join u.unitGroups ug where u.id = 10 and ug.ugKey = 'amount'
    

    【讨论】:

      【解决方案3】:

      试试这个

      select u from  unit as u 
      where u.ID = 10 and 
      'amount' = any elements(u.unitGroups.UGKey)  
      

      【讨论】:

      • 从单元 u 中选择 u,其中 u.id = 10 且 'amount' = 任何元素(u.unitGroups.ugKey):org.hibernate.QueryException:非法尝试取消引用集合 [unit0_.ID。 unitGroups] 与元素属性参考 [ugKey]
      猜你喜欢
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 2011-04-12
      • 2011-02-13
      相关资源
      最近更新 更多