Hibernate Criteria query - Class cast exception

10,447

Solution 1

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.

Solution 2

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();
Share:
10,447

Related videos on Youtube

Raja Chandra Rangineni
Author by

Raja Chandra Rangineni

Updated on June 04, 2022

Comments

  • Raja Chandra Rangineni
    Raja Chandra Rangineni about 2 years

    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.

  • cowls
    cowls over 11 years
    Old question but this line is golden: .setResultTransformer(Transformers.aliasToBean(Summary.class‌​))
  • user1735921
    user1735921 almost 6 years
    Getting this error: Could not instantiate resultclass