如何使用 Hibernate/NHibernate 内连接派生表?
(首先,如果这是重复的,我想道歉,即使它必须很简单,我也找不到任何好的解决方案)
我正在根据销售数据创建报告,并且需要输出一些聚合值以及一些非聚合/非分组值,例如名称。
这就是我想要输出的内容:
每个员工的总利润,其中 User.Name 和 SUM(Order.Profit) 如下所示:
名称利润[+更多聚合列] ------------------- 约翰·多伊 | 250 美元 詹姆斯·史密斯 | 130 美元
这对于普通 SQL 来说相当简单,例如:
SELECT
u.Name,
x.TotalProfit
FROM dbo.Users u
INNER JOIN (
SELECT o.UserID as UserID,
SUM(o.Profit) AS TotalProfit,
--[..] more aggregated columns
FROM Orders o
GROUP BY o.UserID
) x ON u.ID = x.ProfitToID
我不想按 u.Name 分组,因为它会影响性能(请阅读 sqlteam.com)
如何使用 NHibernate 执行此操作?
(First i'd like to apologize if this is a duplicate, I can't find any good solution for it even though it must be simple)
I'm creating reports from sales-data and need to output some aggregated values along with some non-aggregated/non-grouped ones, like Name.
This is what I'd like to output:
Total profit per employee with User.Name and SUM(Order.Profit) like this:
Name Profit [+ more aggregated columns] ------------------- John Doe | $250 James Smith | $130
This is fairly simple with plain SQL like:
SELECT
u.Name,
x.TotalProfit
FROM dbo.Users u
INNER JOIN (
SELECT o.UserID as UserID,
SUM(o.Profit) AS TotalProfit,
--[..] more aggregated columns
FROM Orders o
GROUP BY o.UserID
) x ON u.ID = x.ProfitToID
I don't want to group by u.Name since it will affect performance (Read more about why at sqlteam.com)
How do I do this with NHibernate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
Hibernate
中,您可以在映射中定义连接路径。因此,在Java
中与其他类不相关的类不能自行加入。 Hibernate 是一种 ORM,这是有道理的。尝试创建一个
SQLquery
。其工作方式与普通 HQL 查询几乎相同。然后您将检索包含数据的数组。解析它或使用合适的构造函数创建 DTO。
乌多.
In
Hibernate
you define the join paths in the mappings. So classes not related inJava
with another classes cannot join themselves. Hibernate is an ORM it make sense.Try creating a
SQLquery
. Works pretty much in the same way that ordinary HQL queries.Then you would retrieve an array with the data. Parse it or create a DTO with a constructor that fit.
Udo.
如果您使用像这样的奇特 SQL,只需使用本机查询:
If you're using fancy SQL like that, just use a native query: