tags:

views:

57

answers:

1

I'm trying to find out if it is possible to do the following HQL using the Hibernate Criteria API:

String hql = "select new InitialCount(substring(name, 1,1), count(id)) from Person group by substring(name, 1,1)";

Where InitialCount is a very simple bean with a string and long contructor:

public static class InitialCount {
    private final String initial;
    private final long count;

    public InitialCount(String initial, long count) {
        this.initial = initial;
        this.count = count;
    }
}

Is it possible?

+2  A: 

Try this :

criteria.setProjection(Projections.projectionList()
        .add(Projections.groupProperty("formulaProp").as("initial"))
        .add(Projections.count("id").as("count"))
            ).setResultTransformer(Transformers.aliasToBean(InitialCount.class)).list();        

where formulaProp is a property of person mapped with the formula "substring(name, 1,1)"

ram
If you do this, you must provide setters and getters for the InitialCount attributes.
ram
cool... will try and report back!
p3t0r
It works, thanks; didn't expect it to be that complicated though... and to bad it can do it with constructor setup to maintain immutability.
p3t0r