如何构建 HQL 查询,即自动连接标记为 LAZY 的子表?
我有一些实体:
public class Album extends GenericAuditedEntity {
@OneToMany(fetch = FetchType.LAZY)
private Set<Item> itemSet = new HashSet<Item>();
}
当我像这样运行 HQL 时: em.createQuery("select a from Album a").getResults()
它产生了许多 SQL 查询: 一种用于从相册表中选择数据。像这样:从Album_table中选择....; 对每个获取的行进行一个查询,用于选择项目。像这样: 选择....从 Item_table iwhere i.Album_id = :Album_id;
但是当我运行 em.createQuery(" 选择a.id、b.id 选自专辑a 左连接项目 i ").getResults()
它产生一个 SQL 查询。但它的结果是一些参数的列表,我需要手动将其放入实体中。
我如何自动构建带有连接的 HQL 并自动将结果放入实体中?是否可能?
I have some entity:
public class Album extends GenericAuditedEntity {
@OneToMany(fetch = FetchType.LAZY)
private Set<Item> itemSet = new HashSet<Item>();
}
And when i run HQL like this:
em.createQuery("select a from Album a").getResults()
it produses many SQL queries:
One for select data from Album's table. Smth like this: select .... from Album_table;
And one query for each fetched row, for selecting items. Smth like this:
select .... from Item_table iwhere i.Album_id = :Album_id;
But when i run em.createQuery("
select a.id, b.id
from Album a
left join Item i
").getResults()
it produses one SQL query. But it's result is list of some parameters, that i need put into the entities manually.
How can i build HQL with joins automatically and automatically put the results to the entities? Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要使用 加入获取:
请注意,这有一定的副作用,上面的链接详细描述了这一点。
You need to use join fetch:
Note that there are certain side effects to that, described in detail the above link.
如果您使用
join fetch
,那么您不需要ID,您可以检索实体,因为Hibernate也会在其一级缓存中填充关联但是,如果您正在检索ID但想要填充然后对象/实体考虑使用构造函数
If you are using
join fetch
then you don't need the IDs, you can retrieve the Entity as Hibernate will also populate the association in it's first-level cacheHowever if you are retrieving the IDs but want populated Objects/Entities then consider using a Constructor
不要使用延迟获取。将获取类型设置为 eager
dont use lazy fetching. set fetch type to eager