2010-05-17 134 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>