Search code examples
hibernateselectprojection

how to select specified fields, and return an object (defined by user) list - (hibernate)


Hibernate api doc introduces the Criteria and Projections classes, which can help select specified fields of table and return an Object list.

BUT, i want to get an class A's list (A is defined by myself), thus i can use it as usual object list.

for example,i have a class:

class A {
    String field1;
    String field2;
    String field3;

    String getField1() {
        return field1;
    }
...
}

the table in database has the same fields.

I want to select field1 and field2 only. so I tried:

List<A> list = (List<A>) ession.createCriteria(A.class)
                    .setProjection(Projections.projectionList()
                                 .add(Projections.property("field1"))
                                 .add(Projections.property("field1"))
                                 .list();

It is obviously not correct: java.lang.ClassCastException!!

Is there any way to get a class A's list? i want to use A's method Directly, like:

list.get(0).getField1()

thks.......


Solution

  • If you set a projection on the criteria, the query won't return a list of entities anymore, but a list of arrays of scalars. This is a good thing, since returning a partially loaded entity would result in a multitude of bugs due to invariants being broken (non null fields being null, unloaded associations, etc.).

    So, you should use another kind of object (a value object) to represent the loaded fields :

    List<Object[]> result = criteria.list();
    for (Object[] row : result) {
        AValueObject a = new AValueObject((String) row[0], (String) row[1]);
        // ...
    }
    

    Hibernate can also do this transformation for you, using reflection, using an AliasToBeanResultTransformer or an AliasToBeanConstructorResultTransformer.