Hibernate没外键关联的两个表做联合查询
早几天修改某网站的数据读取缓慢的问题,数据读取主要涉及两个表,Product(产品表),ProductCategory(产品类别关联表).
经过分析源码,得到相应的HQL语句:
from Product qp inner join ProductCategory qpc on where qpc.productId=qp.id and qpc.categoryId = XX and qp.isHot =X order by qp.listId
运行报错:
net.sf.hibernate.QueryException: outer or full join must be followed by path expression [....]
查找相关资料分析结果:
只有两个entity有association的状况下,才能使用join。比如Product and ProductCategory有many-to-one association
再有:HQL中没有“on X= X”这样的语法
修改配置文件多方面不允许,把语句改成:
from Product qp, ProductCategory qpc where qpc.productId=qp.id and qpc.categoryId = X and qp.isHot =X order by qp.listId
但这样返回的是两个对象,List中每一项都是一个对象数组,再次修改语句,加上select qp ;
select qp from Product qp, ProductCategory qpc where qpc.productId=qp.id and qpc.categoryId = X and qp.isHot =X order by qp.listId
新问题:
返回的Product entity有重复的。因为一个流程有多个审批记录,inner join 之后对应每个审批记录都会返回一样的流程
加上distinct语句
select distinct qp from Product qp, ProductCategory qpc where qpc.productId=qp.id and qpc.categoryId = X and qp.isHot =X order by qp.listId
问题解决.
注:是SQL的话,使用 distinct qp.* 可行。但是对于HQL,没法使用 * 来选择属性,它属于一个对象.使用 qp 即可