使用list()hibernate

时间:2015-12-24 09:12:31

标签: java hibernate hql criteria

我有Hibernate criteria查询,如下所示:

Criteria criteria = session.createCriteria(Test.class);
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("Month"));
projList.add(Projections.property("Year"));
criteria.setProjection(Projections.distinct(projList));

这里我试图使用类似于

的月份和年份来获取不同的值

select distinct Month, Year from table;

最后在完成查询后,我使用list()来获取条件:

criteriaList = criteria.list();

现在我的criteriaListObject,其中包含两个列数据MonthYear。我想将criteriaList中只有Month的查询结果列入List<Integer>

我尝试循环浏览criteriaList并将提取的Object转换为List<Integer>,但它无效。如何从返回的两列中仅获取第一列(Month)

注意:将投影设置为只有一列(Month)无效,因为我需要MonthYear

更新

我使用了以下类型:

List<Object[]> criteriaList = Collections.emptyList();
List<Integer> Month = Collections.emptyList();

由于返回的月数会有所不同,我想将获取的月份添加到List<Integer>以执行进一步的操作。

1 个答案:

答案 0 :(得分:0)

如图所示使用ProjectionList时,hibernate会在List<Object[]>上返回criteria.list()。在您的情况下,对象数组第一个元素(0索引)是月,第二个元素(1索引)是年。

所以你必须处理一个对象数组列表,如下所示:

List<Object[]> criteriaList = criteria.list();
List<Integer> monthList = Collections.emptyList();

for (Object[] row : criteriaList) {
    try{
        BigDecimal month = row[0];
        monthList.add(month.intValueExact());
    catch(Exception e){
        //To deal with casting Exception, NPE and 
        //ArithmeticException if int conversion fails
    }

    //Do what you want ...
}

当然,我认为Projections.property("Month")Integer对象,但我不知道,所以你必须正确投射。 Year也一样。

当然,您也可以使用resultTransformer。

修改

在您提供有关评论的更多信息之后,我刚刚编辑了我建议的块。