您好:
我正在使用hibernate3.6,查询时遇到问题。

以这个hql为例:

String hql="select count(distinct ip),sum(bytes) from Entity en where ....
Query q=Session.createQuery(hql);
List<?> list=q.list();


现在,可以通过以下方式从列表中检索列属性:

    String[] properties={"count","sum"};
    for (Object obj : list) {
            Map<String, Object> m = new HashMap<String, Object>();
            Object[] props = (Object[]) obj;
            if(properties.length!=props.length) throw ....
            for (int i = 0; i < props.length; i++) {
                m.put(properties[i], props[i]);
            }
    }


现在,我的问题是,当没有设置hql结果时,计数​​为0,但总和为null。我也想要0。

当然,如果知道db结果表的列名和类型(它们是上面示例中的count,sum),则可以显式进行转换,但是现在我不知道。

就是说,我不能使用这样的东西:

if(props[i]=null) props[i]=0;
m.put(properties[i], props[i]);


由于props [i]的类型可以是字符串,因此在这种情况下,如果其值为null,则应为“”。

所以我想知道是否可以在hql单词中区分转换类型?也许像这样:


选择计数(不同
ip),来自实体en的(long)sum(bytes)
在...

选择计数(不同的ip),(转换
..sum(bytes))来自实体en
....


这可能吗?

BWT,我使用mysql 5.1。

谢谢。

更新:
@ zinan.yumak:

您的答案似乎是这样;

select new Wrapper(count(distinct ip),sum(bytes)) from Entity en where...


如果是这样,我必须创建像Wrapper这样的额外类,因为我的appliction中有很多选择类型,例如:

select new AnotherWrapper(broswer,count(distinct brower)) from Entity en where...

......

最佳答案

我认为您需要的是结果转换器。为您的查询创建一个模型类。
然后将null检查或其他检查添加到您的setter方法中。像这样

String hql="select count(distinct ip) as ip, sum(bytes) as bytes from Entity en where ....
Query q=Session.createQuery(hql).setResultTransformer(Transformers.aliasToBean(Model.class));


在您的Model课中

class Model {
    private String ip = "";
    private BigDecimal bytes = BigDecimal.ZERO;

    public void setIp(String anIp) {
        if ( aString != null) {
            this.ip = anIp;
        }
    }

    public void setBytes(String aByte) {
        if ( aByte != null) {
            this.byte = aByte;
        }
    }
    .
    .
    .
}

10-07 12:42
查看更多