我目前正面临性能问题。我最近将SQL查询转换为HQL,以简化大量的1-1,1-M加入,现在我的聚合函数(count,sum,avg)只能用作@Formula
。 @Formula
的主要问题是每个结果行的子选择,很多时候我需要10到600个结果行,总查询时间很长......
HQL查询:
select
cp,
count(cr) as ratingsCount, // What I was using in SQL
avr(cr.rate) as ratingsAverage // What I was using in SQL
from Post cp
left join fetch cp.titles cmtt
left join fetch cp.contents cmtc
left join fetch cp.paths cmtp
left join fetch cp.categories
left join fetch cp.properties
left join fetch cp.userCreator
left join fetch cp.userUpdater
left join Rating r
on r.keyPost = cp.keyPost
group by
cp
实体:
@Entity
@Table(name="common_posts")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
@DiscriminatorValue(value = "post")
public class Post implements Serializable
{
/* ... */
public void setRatingsAverage(Double p_dRatingsAverage)
{
m_dRatingsAverage = p_dRatingsAverage;
}
// What I'm currently using...
@Formula("(SELECT AVG(cr.rate) FROM common_ratings cr WHERE cr.keyPost = keyPost)")
// What I've tested but doesn't work, was working in plain SQL
//@Column(name = "ratingsAverage")
// What I've also tested but doesn't work
//@Formula("(ratingsAverage)")
public Double getRatingsAverage()
{
return m_dRatingsAverage;
}
public void setRatingsCount(Integer p_iRatingsCount)
{
m_iRatingsCount = p_iRatingsCount;
}
@Formula("(SELECT COUNT(*) FROM common_ratings cr WHERE cr.keyPost = keyPost)")
//@Column(name = "ratingsCount")
public Integer getRatingsCount()
{
return m_iRatingsCount;
}
}
我想要一个没有子查询且没有普通SQL的解决方案。