使用hibernate进行复杂查询(如每个组的前n个)的最佳方法 [英] Best way to use hibernate for complex queries like top n per group

查看:63
本文介绍了使用hibernate进行复杂查询(如每个组的前n个)的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在使用hibernate来定义我的查询的报告应用程序上工作了一段时间。然而,越来越多的人认为,报告用例并不是最好的方法。

1)查询只产生部分列,因此没有类型化对象(除非你在java中投射所有字段)。
2)很难在不直接进入sql或hql的情况下表达查询。



我现在的问题是我想要得到每个组的前N个,例如一个组中的每个元素的最后5天,其中每天我都会显示访问者的数量。



结果应该如下所示:

  | RowName | 1-1-2009 | 2-1-2009 | 3-1-2009 | 4-1-2009 | 5-1-2009 
| SomeName | 1 | 42 | 34 | 32 | 35

将每天每行存储的数据转换为输出的最佳方法是什么这个?是时候回到普通的sql并使用无类型的数据了吗?



我真的想为我的结果使用类型化对象,但是java让我的生活变得相当困难。欢迎任何建议!

解决方案

使用Criteria API,您可以执行此操作:

  Session session = ...; 
Criteria criteria = session.createCriteria(MyClass.class);
criteria.setFirstResult(1);
criteria.setMaxResults(5);
...任何其他标准...
List topFive = criteria.list();

要在vanilla SQL中执行此操作(并确认Hibernate正在按照您的期望执行操作) a so href =https://stackoverflow.com/questions/595123/is-there-an-ansi-sql-alternative-to-the-mysql-limit-keyword>这个SO贴子:


I'm working now for a while on a reporting applications where I use hibernate to define my queries. However, more and more I get the feeling that for reporting use cases this is not the best approach.

1) The queries only result partial columns, and thus not typed objects (unless you cast all fields in java). 2) It is hard to express queries without going straight into sql or hql.

My current problem is that I want to get the top N per group, for example the last 5 days per element in a group, where on each day I display the amount of visitors.

The result should look like:

| RowName | 1-1-2009 | 2-1-2009 | 3-1-2009 | 4-1-2009 | 5-1-2009
| SomeName| 1        | 42       | 34       | 32       | 35

What is the best approach to transform the data which is stored per day per row to an output like this? Is it time to fall back on regular sql and work with untyped data?

I really want to use typed objects for my results but java makes my life pretty hard for that. Any suggestions are welcome!

解决方案

Using the Criteria API, you can do this:

Session session = ...;
Criteria criteria = session.createCriteria(MyClass.class);
criteria.setFirstResult(1);
criteria.setMaxResults(5);
... any other criteria ...
List topFive = criteria.list();

To do this in vanilla SQL (and to confirm that Hibernate is doing what you expect) check out this SO post:

这篇关于使用hibernate进行复杂查询(如每个组的前n个)的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆