Search code examples
hibernatecriteriahibernate-criteria

Criteria to list of Entityinstance+Extrafield


im pretty sure this question anywhere already has been asked anywhere - didnt found the answer.

I got an simple Criteria like this:

s.createCriteria(Human.class).list()

gives me an resultlist of entityinstance of Human (gender and name).

Can i add an calculation like "salutation" to the resulting entityinstances only (without changing Human.java) and avoid the creation of an 2-dimensional array?

I know, this should be the job of such an Decorator-Class, is there any workaround? The enlarged entityinstance should extends the Human-class!


Solution

  • No, it's not completely possible. A Criteria query can only return entities, arrays of scalars, or value objects built from scalars (using a ResultTransformer).

    You could return a list of HumanWithSalutation objects, which would hold the same fields as a Human + an additional salutation one, but these would be value objects, and not persistent objects: any modification made to these objects would not be made persistent to the database as it would be with Human instances.

    To do that, create the class :

    public class HumanWithSalutation extends Human {
        private String salutation;
    
        // getter and setter
    }
    

    Assign it an AliasToBeanResultTransformer (which will populate all your HumanWithSalutation objects using setters), and make sure the criteria has a projection list returning all the fields of Human + the salutation (aliased to "salutation"):

    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.property("id");
    projectionList.add(Projections.property("name");
    projectionList.add(Projections.property("gender");
    projectionList.add(Projections.alias(Projections.sqlProjection(...), "salutation"));
    criteria.setProjection(projectionList);
    

    If you don't want the SQL projection, you could implement the transformation in Java in the getSalutation() method (and remove the setter).