2012-01-18 54 views
0

在路口表條目我有三個表:獲取基於關鍵

offers; offer_groups; offer_group_members. 

offersoffer_groups表映射與Hibernate(見下文)。

offer_group_members中,我存儲了優惠屬於哪個組(提供主鍵,優惠組主鍵)。

我有點新的休眠,所以我的問題是:我如何根據Offer鍵從OFFER_GROUP_MEMBERS表中得到所有OfferGroups

我想是這樣的:

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> 

回答

0

,如果你向我們展示了實體會更容易些,因爲這是對他們HQL和標準的查詢工作。

不管怎樣,在HQL:

select og from Offer o 
inner join o.offerGroups og 
where o.key = :key 

而且在標準,不幸的是,IIRC,所有你能做的就是選擇根實體或標量,所以很難做到這一點,而無需一個bidirectionall關聯。如果你有一個雙向關聯,你可以做

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。