使用 fetch/select 的 Hibernate 语法
我在使用休眠混合和匹配获取和选择时遇到一些问题。 基本上,我在用户表中列出了一堆用户,该表还包含一个“createdBy”列,该列通过 id 引用用户表 例如:
id | name | foo | createdBy
----------------------------
1 abc zzz 2
2 def zzz 2
所以,在上面的示例中,我希望为“abc”的createdBy列返回“def”用户的实例
因此,如果没有createdBy,我的查询如下所示:
from User u inner join fetch e.foo as foo inner join fetch foo.bar as bar
我如何将其插入
"select User u2 from User where u2.id=u.createdBy"
到上一个查询中?
I am having some trouble mixing and matching fetches and selects using hibernate.
Basically, I am listing a bunch of users in a user table which also contains a "createdBy" column which references the user table by id
Ex:
id | name | foo | createdBy
----------------------------
1 abc zzz 2
2 def zzz 2
So, In the example above I would want an instance of the "def" user to be returned for "abc"'s createdBy column
So, without the createdBy, my query looks like:
from User u inner join fetch e.foo as foo inner join fetch foo.bar as bar
How would I insert the
"select User u2 from User where u2.id=u.createdBy"
into the previous query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
createdBy
在User
实体中映射为惰性ManyToOne
,您将按照与其他联接完全相同的方式将其包含在查询中:假设 它没有映射为
ManyToOne
(为什么不?),而是仅映射其ID,您必须使用交叉联接并且您必须转换查询结果(通过自定义构造函数或ResultTransformer
实现)或将它们作为List
使用,因为这就是它们的样子:不用说,第一个选项(映射
createdBy< /code> as
ManyToOne
)要简单得多。Assuming
createdBy
is mapped in theUser
entity as lazyManyToOne
you would include it in your query in the exact same fashion as your other joins:If it's not mapped as
ManyToOne
(why not?) and instead only its ID is mapped, you'll have to use a cross join AND you will either have to transform query result (via custom constructor orResultTransformer
implementation) or consume them asList<Object[]>
as that's what they'll be:Needless to say, the first option (mapping
createdBy
asManyToOne
) is much more straightforward.