2010-05-17 136 views
2

在Hibernate HQL中,您將如何通過多對多關聯進行查詢。如果我有一家公司擁有多個ProductLines,而其他公司可以提供這些相同的產品線,我有一個公司實體,一個ProductLine實體和一個關聯表CompanyProductLine。在SQL中,我能得到什麼,我需要這樣的:查詢休眠多對多關聯

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

我的問題看到同睡我在Company.hbm.xml文件中定義的關聯關係:

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

任何HQL我似乎拿出就會拋出一個:「期待‘元素’或「指數」「休眠例外

思考什麼正確的HQL是

回答

4

你的HQL查詢應該是這樣的:?

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

和映射這樣的:

<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>