JPA 通过避免 JOIN 查找表来优化查询?
想象一下表 emp:
CREATE TABLE emp
( id NUMBER
, name VARCHAR
, dept_code VARCHAR
)
和表 dept:
CREATE TABLE dept
( code VARCHAR
, name VARCHAR
)
emp.dept_code
将 dept.code
引用为外键。
这些表映射到 JPA 实体,并且将外键建模为关联:
@ManyToOne
@JoinColumn(name = "dept_code")
private Department department;
给定以下数据:
emp dept
---------------- ------------------
1 John SALS SALS Sales
2 Louis SALS SUPT Support
3 Jack SUPT
4 Lucy SUPT
我想编写一个返回支持部门中所有员工的 JPA 查询。假设我知道支持部门的主键 (SUPT
),
我猜这将是:
SELECT emp
FROM Employee emp JOIN emp.department dept
WHERE dept.code = 'SUPT'
问题:
作为部门键 SUPT< /code> 代码在 emp 表中可用,有没有办法重写 JPA 查询通过避免连接到部门实体?
这会带来性能提升吗?或者 JPA 实现(如 Hibernate)是否足够智能,可以避免数据库连接到 dept 表?
Imagine a table emp:
CREATE TABLE emp
( id NUMBER
, name VARCHAR
, dept_code VARCHAR
)
and a table dept:
CREATE TABLE dept
( code VARCHAR
, name VARCHAR
)
emp.dept_code
references dept.code
as a ForeignKey.
These tables are mapped to JPA Entities, and the ForeignKey is modeled as an association:
@ManyToOne
@JoinColumn(name = "dept_code")
private Department department;
Given following data:
emp dept
---------------- ------------------
1 John SALS SALS Sales
2 Louis SALS SUPT Support
3 Jack SUPT
4 Lucy SUPT
I would like to write a JPA query that returns all Emloyees in the Support Department. Assume I know the PrimaryKey of the Support Department (SUPT
)
I guess that would be:
SELECT emp
FROM Employee emp JOIN emp.department dept
WHERE dept.code = 'SUPT'
Question:
As the Department key SUPT
code is available in the emp table, is there a way to rewrite the JPA query by avoiding the JOIN to the Department Entity?
Would this result in a performance improvement? Or is a JPA implementation (like Hibernate) smart enough to avoid the database join to the dept table?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您通常会将查询编写为
并让您的提供商找出得出结果的最佳方法。就休眠而言,是的,它足够聪明,意识到它可以只查看连接列。
编辑:值得注意的是,您尚未在注释中设置延迟加载,因此无论如何它都会加入表以创建部门实体:)
You would usually write the query as
and let your provider figure out the best way to come up with the result. In the case of hibernate, yes, it is smart enough to realize it can just look at the join column.
edit : It is worth noting, that you haven't set up lazy loading in your annotations, so it's going to join the table in to create the department entity anyway :)