Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Criteria Projection

Well as the question title 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.

like image 710
Darwly Avatar asked Dec 28 '22 07:12

Darwly


1 Answers

You can use criteria.setResultTransformer()

There's some Transformers provided in Hibernate. If your Person has not any association use this:

criteria.setResultTransformer(Transformers.aliasToBean(Person.class));

But if Person has any association, consider use Seimos at http://github.com/moesio/seimos

A lot of code could be saved if you use it instead Criteria.

like image 50
Moesio Avatar answered Dec 30 '22 22:12

Moesio