views:

757

answers:

3

Hello everyone,

I am using Hibernate(3.2) Criteria for querying and its giving me exception when converting to a list.

Please see my code and exception below:

    List<Summary> summaryList;
    Criteria criteria = session.createCriteria(Summary.class);
    session.beginTransaction();
    summaryList = Criteria.setProjection(
      Projections.projectionList().add(Projections.sum("contractDollar"))
      .add(Projections.groupProperty("department"))).list() ;

exception: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.abc.model.Summary

I am not sure why the result is returned as 'Object' even though I specified it as my pojo(Summary)

Could you please help me with this. I am a newbie to hibernate.

Thanks, Raja.

A: 

Have you specified a ResultTransformer ?

Frederik Gheysels
Hi Frederik,I have specified below ResultTransformers and results in following exceptions:setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list()Exception : java.lang.String cannot be cast to com.bbn.model.Summary .setResultTransformer(Transformers.TO_LIST).list() Exception: .setResultTransformer(Transformers.TO_LIST).list() Could you please help me.Raja.
Raja Chandra Rangineni
A: 

Is Summary a mapped entity or a bean you're trying to return in your results? It shouldn't be both. You need to pass an entity class into session.createCriteria().

As far as results go, you need to:

  1. Have an appropriate setter in your Summary class (or your result bean if it's different).
  2. Specify an alias for your projection.
  3. Specify an 'aliasToBean' result transformer.

Your criteria code will become:

summaryList = Criteria.setProjection(
 Projections.projectionList()
  .add(Projections.sum("contractDollar"), "contractSum")
  .add(Projections.groupProperty("department"))
 )
.setResultTransformer(Transformers.aliasToBean(Summary.class))
.list() ;

Your Summary bean will need to have a setContractSum() method in this example.

ChssPly76
A: 

I'm not sure what Summary is but try:

Criteria criteria = session.createCriteria(Summary.class);
Transaction tx = session.beginTransaction();
summaryList = criteria.setProjection(
    Projections.projectionList().add(Projections.sum("contractDollar"))
      .add(Projections.groupProperty("department"))).list() ;

Object[] result = criteria.list().get(0);
// result[0] holds the sum of contractDollar

tx.commit();
Manuel Darveau