views:

120

answers:

2

Well as the question says, i am trying to make a projection criteria querying only couple of the table attributes. So I have a Person Table/class and it has about 40 attributes i want my criteria to get dynamical number of attributes, lets say 10, 11 or 12.(sql terms "select firstname, lastname from person") and i was doing it like this

Transaction tx = session.beginTransaction();
Criteria crit = session.createCriteria(Person.class);
crit.setCacheable(true);
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("id"));
Criterias c = null;
 for (int i = 0; i < checked.size(); i++) {
        Attribute attr = checked.elementAt(i);
        switch (attr) {
            case LASTNAME:
                projList.add(Projections.property("lastName"));
                c = enumMap.get(attr);
                if (c.isChanged()) {
                    String tmp = (String) c.getAnswer();
                    tmp = tmp.replace('*', '%');
                    crit.add(Restrictions.like("lastName", tmp));
                    crit.addOrder(Order.asc("lastName"));
                }
            case ...THE REST .....
            }
    crit.setProjection(projList);
    retList = crit.list();
    tx.commit();
    return retList;

and it gives back that the retList elements are not from the Person.class ..

INFO [AWT-EventQueue-0] (UserGroupManagerApp.java127) - [Ljava.lang.Object;@14b9b80 FATAL [AWT-EventQueue-0] (Login.java78) - java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to usergroupmanager.model.db.Person java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to usergroupmanager.model.db.Person

please help, For now i am listing all the 40+ attr, and it takes up querying time and i do not like it. i am looking also an alternative solution which will help me solve this. I read about ResultTransformer but havent found how to use it in my case. pls help, tnx

+1  A: 

[Ljava.lang.Object; cannot be cast to usergroupmanager.model.db.Person

Says in clean words Object[] cannot be cast to Person. When you do a projection, you will get the attributes you selected as an array of objects instead of a hydrated entity.

Your code is missing the declaration of retlist. I guess it's a raw List which you cast to a List<Person> somewhere. Just replace that with List<Object[]>.

Willi
thank you, i figured it out eventually but it was frustrating at that time.. Thanks a bunch
DartesMartes
A: 

If you use a projection in Hibernate you are not querying all the data Hibernate needs to create the objects. Thus Hibernate cannot create the objects.

Thus the query from a projection just returns an array of the SQL returned from the query ie it returns a s List and you access the fields as plain entries in that array.

Mark