我有三张桌子:
offers; offer_groups; offer_group_members.offers和offer_groups表映射为hibernate (见下文)。
在offer_group_members中,我存储报价属于哪个组(提供主键,提供组主键)。
我对hibernate有点陌生,所以我的问题是:OfferGroups如何根据提供键从 OFFER_GROUP_MEMBERS 表中获取所有?
我试过这样的方法:
Criteria crit;
crit = getSession().createCriteria(Offer.class);
crit = crit.createCriteria("offerGroups");
crit.add(eq("key", offerKey));以下是映射:
报盘:
<composite-id name="comp_id"
class="com.infonova.psm.hibernate.prodsrv.OfferPK">
<key-property name="key" column="KEY"
type="java.lang.String" length="128">
</key-property>
</composite-id> 对于offer_group_key:
<id name="key" type="java.lang.String" column="KEY" length="128">
<generator class="assigned"/>
</id>`对于offer_group_key:
<set name="offers" table="OFFER_GROUP_MEMBERS" lazy="true" inverse="false"
cascade="none">
<key>
<column name="OFFER_GROUP_KEY"/>
</key>
<many-to-many class="Offer">
<column name="OFFER_KEY"/>
</many-to-many>
</set>报盘:
<set name="offerGroups" table="OFFER_GROUP_MEMBERS"
inverse="true" lazy="true" cascade="none">
<key>
<column name="OFFER_KEY" />
</key>
<many-to-many
class="OfferGroup">
<column name="OFFER_GROUP_KEY" />
</many-to-many>
</set>发布于 2012-01-18 15:35:18
如果您向我们展示实体,会更容易一些,因为HQL和条件查询是在它们上工作的。
总之,在HQL:
select og from Offer o
inner join o.offerGroups og
where o.key = :key不幸的是,在标准中,IIRC所能做的就是选择根实体或标量,所以如果没有双向的关联,就很难做到这一点。如果你有双向关联,你可以
Criteria c = session.createCriteria(OfferGroup.class, "og");
c.createAlias("og.offers", "o");
c.add(Restrictions.eq("o.key", key));由于您没有双向关联,我所知道的唯一方法就是这样做:
Criteria c = session.createCriteria(OfferGroup.class, "og");
DetachedCriteria dc = DetachedCriteria.forClass(Offer.class, "o");
dc.createAlias("o.offerGroups", "og2");
dc.add(Restrictions.eq("o.key", key));
dc.setProjection(Projections.property("og2.id"));
c.add(Subqueries.propertyIn("og.id", dc));它对应于这个丑陋的HQL查询:
select og from OggerGroup og
where og.id in (select og2.id from Offer o
inner join o.offerGroups og2
where o.key = :key)对于这样简单的静态查询,我认为没有理由使用标准而不是HQL。
https://stackoverflow.com/questions/8912154
复制相似问题