如何将hibernate查询结果作为列表或hashmap的关联数组获取
我正在开发struts 2和hibernate 3中的应用程序。
我有3张桌子
- 检查
- InspectionMission
- 时间线
Inspection
与InspectionMission
相关联,而InspectionMission
与Timeline
相关联。
现在我有以下问题。 我在HQL中编写了以下查询
public List getQuartewiseInspectionList(){ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Query q = session.createQuery( "select count(i.inspectionId) as tot_inspections,t.year,t.quarter" + " From Inspection as i " + " inner join i.inspectionMission as im inner join im.timeline as t" + " GROUP by t.year,t.quarter"); return q.list(); }
我想获取结果如下
result[0][tot_inspections] = "6" result[0][year] = "2009"; result[0][quarter] = "Q2"; result[1][tot_inspections] = "3" result[1][year] = "2009"; result[1][quarter] = "Q3";
等等,以便我可以在jsp struts中显示它,如下所示:
在JSP中,我编写了以下代码
<tr class="evenodd">
这里有人可以帮助我吗?
你必须使用“新地图”语法(Hibernate Reference第14.6段)
select new map(count(i.inspectionId) as tot_inspections, t.year as year, t.quarter as quarter) from ...
查询的其余部分是相同的。 这将返回一个映射列表,其中键是“列”的别名。
另一种解决方案是定义一个数据对象,仅用于显示这些结果,让Hibernate动态创建实例。 这个类只需要一个匹配的构造函数。
示例类(省略了getters和字段)
public class InspectionCount() { // fields public InspectionCount(int count, int year, int quarter) { // initialize instance } // getters }
然后查询将查找
select new InspectionCount(count(i.inspectionId), t.year, t.quarter) from Inspection as i inner join i.inspectionMission as im inner join im.timeline as t group by t.year,t.quarter
因此,您将获得一个InspectionCount
List
。
- Jersey,Guice和Hibernate – EntityManager线程安全
- JPA / Hibernate DDL生成; CHAR与VARCHAR
- getSingleResult在hibernate中返回本机标量查询的代理
- 代理如何加载Hibernate / JPA中的惰性属性
- org.hibernate.hql.internal.ast.QuerySyntaxException:表未映射
- 使用Transformer时HibernateexceptionPropertyNotFoundException
- 在hibernate实体上处理数据库视图的优雅方法?
- 在WebLogic中运行时ClassNotFoundException(HqlToken)
- 从无状态Bean中获取JDBC Connection对象