使用 fetch/select 的 Hibernate 语法

发布于 2024-12-17 16:06:54 字数 511 浏览 0 评论 0原文

我在使用休眠混合和匹配获取和选择时遇到一些问题。 基本上,我在用户表中列出了一堆用户,该表还包含一个“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你与清晨阳光 2024-12-24 16:06:54

createdByUser 实体中映射为惰性 ManyToOne,您将按照与其他联接完全相同的方式将其包含在查询中:

from User u
  join fetch u.foo as foo
  join fetch foo.bar as bar
  join fetch u.createdBy

假设 它没有映射为ManyToOne(为什么不?),而是仅映射其ID,您必须使用交叉联接并且您必须转换查询结果(通过自定义构造函数或ResultTransformer 实现)或将它们作为 List 使用,因为这就是它们的样子:

select u, u2
  from User u, User u2
    join fetch u.foo as foo
    join fetch foo.bar as bar
 where u.createdBy = u2.id

不用说,第一个选项(映射 createdBy< /code> as ManyToOne)要简单得多。

Assuming createdBy is mapped in the User entity as lazy ManyToOne you would include it in your query in the exact same fashion as your other joins:

from User u
  join fetch u.foo as foo
  join fetch foo.bar as bar
  join fetch u.createdBy

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 or ResultTransformer implementation) or consume them as List<Object[]> as that's what they'll be:

select u, u2
  from User u, User u2
    join fetch u.foo as foo
    join fetch foo.bar as bar
 where u.createdBy = u2.id

Needless to say, the first option (mapping createdBy as ManyToOne) is much more straightforward.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文