hguser
hguser

Reputation: 36068

can I specify the return type in the hql words

Hi: I am using hibernate3.6,I meet some problem when do some querying.

Take this hql for exmaple:

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

Now I can retrive the columen properties from the list by the following way:

    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]);
            }
    }

Now,my problem is that,when the hql result no set,the count is 0,but the sum is null. I want it 0 also.

Of course,I can do the converting explicitly if the know the column name and type(they are the count,sum in the above example) of the result table from db,but now I did not know.

That's to say,I can not use something like this:

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

Since the type of props[i] may be string,in this case if its value is null, it should be "".

So I wonder if I can sepcify the converting type in the hql words? maybe someting like this:

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

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

Is this possible?

BWT,I use mysql 5.1.

Thanks.

UPDATE: @zinan.yumak:

Your answer seems like this;

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

If so I have to create enougth extra class like Wrapper since there are so many types of select in my appliction.like:

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

......

Upvotes: 0

Views: 4975

Answers (1)

zinan.yumak
zinan.yumak

Reputation: 1590

I think what you need is a result transformer. Create a model class for your query. Then add null checks or other checks into your setter methods. Something like this,

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));

And in your Model class,

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;
        }
    }   
    .
    .
    .
}

Upvotes: 1

Related Questions