Hibernate Criteria Projection of non scalar values

泪湿孤枕 提交于 2019-12-08 13:35:10

问题


Is there any way to project multiple values for an root entity object using Criteria?

Assume we have these classes (With the proper mappings):

   class Boss {
        private String name;
        private List<Employee> employees;

        // setters and getters and more stuff
   }

   class Employee {

        private String name;

        // setters and getters and more stuff
   }

Then i am trying to do this :

   public void test() {
        Criteria criteria = this.getSession().createCriteria(Boss.class);

        criteria.createAlias("employees","employees");

        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.property("name"), "name");
        projectionList.add(Projections.property("employees.name"), "subordinatesNames"); 
        criteria.setProjection(projectionList);

        criteria.setResultTransformer(new AliasToBeanResultTransformer(BossBean.class));
        List<BossBean> results = criteria.list(); // fails here
        for (BossBean bossBean : results) {
            System.out.println (bossBean);
        }
    }

This is how the Bean looks like (nothign special, just for grouping values) :

public static class BossBean {
    private String name;
    private List<Strings> subordinatesNames;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Strings> getSubordinatesNames() {
        return subordinatesNames;
    }

    public void setSubordinatesNames(List<Strings> subordinatesNames) {
        this.subordinatesNames = subordinatesNames;
    }

}

The exception is this :

2014-06-06 13:37:38 [main] ERROR org.hibernate.property.BasicPropertyAccessor - expected type: java.util.List, actual value: java.lang.String.

I Guess is trying to fit the String returned from Boss(root object) -> (A)Employee(association) ->name(value) into a List.

I want to auto magically get all inserted in the List. Is there a way to achieve this using Criteria? If not, how i can achieve it?

Thanks in advance!

Grettings

Víctor

来源:https://stackoverflow.com/questions/24087605/hibernate-criteria-projection-of-non-scalar-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!