This was my solution.
this more-enhanced version lets you place the query results directly into a stone-simple
Java class that is =NOT= managed by Hibernate. Great for generating reports where
you'd like to have a class that corresponds to your query row but don't need to store it in a
database table.
The fields in the POJO exactly match up with the columns in the query.
Assume you have a POJO named RptW
Code:
public class RptW implements java.io.Serializable
{ // report class doesn't need an id
private String code;
private Long genderMale; // need Long to hold SUM(*)
private Long genderFemale;
private Long tot;
//constructors
public RptW() {}
public RptW(String code, Long genderMale, Long genderFemale, Long tot) {
this.code = code;
this.genderMale = genderMale;
this.genderFemale = genderFemale;
this.tot = tot;
}
//getters and setters
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Long getGenderMale() {
return genderMale;
}
public void setGenderMale(Long genderMale) {
this.genderMale = genderMale;
}
public Long getGenderFemale() {
return genderFemale;
}
public void setGenderFemale(Long genderFemale) {
this.genderFemale = genderFemale;
}
public Long getTot() {
return tot;
}
public void setTot(Long tot) {
this.tot = tot;
}
@Override
public String toString() {
return "RptW [code=" + code + ", genderMale=" + genderMale
+ ", genderFemale=" + genderFemale + ", tot=" + tot + "]";
}
}
and in the executable
Code:
java.util.List<RptW> results = null; // note the direct creation of RptW objects instead of usual Object[]
RptW result;
ListIterator<RptW> ui = null;
String sqlcmd;
sqlcmd = "SELECT vv.code AS code, " +
" SUM( vv.genderMale) AS genderMale, " +
" SUM( vv.genderFemale) AS genderFemale, " +
" SUM( vv.tot) AS tot " +
" FROM Employees AS vv " +
" GROUP BY vv.code ";
Query hqlQuery = this.sessB.createSQLQuery(sqlcmd)
.addScalar("code", Hibernate.STRING) // Hibernate magic here!
.addScalar("genderMale", Hibernate.LONG)
.addScalar("genderFemale", Hibernate.LONG)
.addScalar("tot", Hibernate.LONG)
.setResultTransformer(Transformers.aliasToBean(RptW.class)); // more magic here
results = hqlQuery.list();
//verify it worked
System.out.println("Q: number of rows:" + results.size() );
ui = results.listIterator();
while( ui.hasNext()) {
result = ui.next();
System.out.println( result.toString());
}
I think this is a powerful technique, hope others enjoy it!
CASE CLOSED
Still-learning Steve