我有两个JPA实体
public class Job {
@ManyToOne
@JoinColumn(name = "service")
public Service service;
@Column(name = "queue_time")
public Long queueTime;
@Column(name = "run_time")
public Long runTime;
}
public class Service {
@Id
@Column(name = "id")
public Long id;
@Column(name = "name")
public String name;
@Column(name = "host")
public String host;
}
现在我想用JPQL进行一些聚合查询:
SELECT job.service.id, AVG(job.queueTime), AVG(job.runTime) FROM Job job GROUP BY job.service.id
生成的SQL查询(我使用的是MySQL数据库)如下所示:
SELECT t0.id, AVG(t1.queueTime), AVG(t1.runTime) FROM Service t0, Job t1 WHERE (t0.service = t1.id) GROUP BY t0.id
如您所见,JPA将我的JPQL查询转换为带有连接的SQL查询。然而,这会大大减慢查询速度。以下SQL查询执行速度提高约6倍,并返回完全相同的结果集:
SELECT t1.service, AVG(t1.queueTime), AVG(t1.runTime) FROM Job t1 GROUP BY t1.service
如果我将JPQL查询更改为
SELECT job.service, AVG(job.queueTime), AVG(job.runTime) FROM Job job GROUP BY job.service
生成的SQL查询如下所示:
SELECT t0.id, t0.name, t0.host AVG(t1.queueTime), AVG(t1.runTime) FROM Service t0, Job t1 WHERE (t0.service = t1.id) GROUP BY t0.id, t0.name, t0.host
有没有办法编写只用 查询作业表而不连接服务表的JPQL?
答案 0 :(得分:0)
这个问题为我解决了这个问题:How can I retrieve the foreign key from a JPA ManyToOne mapping without hitting the target table?
我采用了第二种解决方案(b)使用FK的只读字段)