Hibernate Criteria query - Class cast exception
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:
- Have an appropriate setter in your Summary class (or your result bean if it's different).
- Specify an alias for your projection.
- 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();
Related videos on Youtube
Raja Chandra Rangineni
Updated on June 04, 2022Comments
-
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 over 11 yearsOld question but this line is golden:
.setResultTransformer(Transformers.aliasToBean(Summary.class))
-
user1735921 almost 6 yearsGetting this error: Could not instantiate resultclass