2010-05-17 6 views
2

Dans Hibernate HQL, comment interroger une association many-to-many. Si j'ai une entreprise avec plusieurs ProductLines et que d'autres sociétés peuvent offrir ces mêmes lignes de produits, j'ai une entité Company, une entité ProductLine et une table d'association CompanyProductLine. Dans SQL, je peux obtenir ce que je veux comme ceci:Interrogation d'une association plusieurs-à-plusieurs Hibernate

select * from company c where c.companyId in (select companyId from companyProductLine cpl, productline pl where cpl.productLineId = pl.productLineId and pl.name= 'some value'); 

voit mon problème de mentir avec l'association I défini dans le fichier Company.hbm.xml:

<set name="productLines" 
    cascade="save-update" 
    table="CompanyProductLine"> 
    <key column="companyId"/> 
    <many-to-many class="com.foo.ProductLine" column="productLineId" /> 
</set> 

Tout HQL Je semble venir avec jetteront un: « attendre des « éléments » ou « indices » » exception Hibernate

pensées sur ce que le HQL approprié serait

Répondre

4

Votre requête HQL devrait ressembler à ceci:.?

from Company c join c.productLines pl where pl.name = :name 

Et cartographie comme ceci:

<hibernate-mapping> 
    <class name=com.example.ProductLine" table="productLine"> 
     <cache usage="read-write"/> 
     <id name="id" column="id" type="long"> 
      <generator class="native"/> 
     </id> 
     <property name="name" column="name"/> 
    </class> 
</hibernate-mapping> 

<hibernate-mapping> 
    <class name="com.example.Company" table="company"> 
     <cache usage="read-write" /> 
     <id name="id" column="id" type="long"> 
      <generator class="native" /> 
     </id> 
     <set name="productLines" table="companyProductLine" lazy="false"> 
      <key column="companyId" /> 
      <many-to-many class="com.example.ProductLine" column="productLineId" /> 
     </set> 
    </class> 
</hibernate-mapping> 
Questions connexes