带有集合ArrayIndexOutOfBoundsException的Hibernate投影

时间:2014-02-12 13:48:35

标签: java hibernate

大家好我有这段代码:

Criteria criteria = session.createCriteria(Department.class);

ProjectionList properties = Projections.projectionList();
properties.add(Projections.property("id"), "id");
properties.add(Projections.property("name"), "name");
properties.add(Projections.property("children"), "children");

criteria.setProjection(properties);
criteria.setFetchMode("children", FetchMode.JOIN);
criteria.setResultTransformer(Transformers.aliasToBean(Department.class));

criteria.add(Restrictions.isNull("parent.id"));
criteria.add(Restrictions.eq("active", true));

return criteria.list();

和实体类

public class Department extends Model {

    @Size(max = 200)
    private String name;

    @Size(max = 10)
    private String sg;

    @Size(max = 1000)
    private String description;

    @ManyToOne
    @JoinColumn(name = "id_parent")
    private Department parent;

    private boolean active;

    @OneToMany(mappedBy = "parent")
    private List<Department> children;

...加上吸气剂和制定者......

我执行标准并给我stacktrace异常:

java.lang.ArrayIndexOutOfBoundsException: 2
at org.hibernate.loader.criteria.CriteriaLoader.getResultRow(CriteriaLoader.java:166)
at org.hibernate.loader.criteria.CriteriaLoader.getResultColumnOrRow(CriteriaLoader.java:146)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:747)
at org.hibernate.loader.Loader.processResultSet(Loader.java:949)
at org.hibernate.loader.Loader.doQuery(Loader.java:917)
at 

我做错了什么?

提前感谢。

1 个答案:

答案 0 :(得分:2)

如果不知道您要对该投影查询做什么,很难说如何修复它。我认为您的主要问题是您需要为子项创建别名,然后在投影中使用该别名。在您的投影中,您还需要引用子项的属性。你可以这样做:

Criteria criteria = session.createCriteria(Department.class);

ProjectionList properties = Projections.projectionList();
properties.add(Projections.property("id"), "id");
properties.add(Projections.property("name"), "name");
properties.add(Projections.property("children.id"), "id");
properties.add(Projections.property("children.name"), "name");

criteria.setProjection(properties);
criteria.createAlias("children",  "children", JoinType.FULL_JOIN);
criteria.setResultTransformer(Transformers.aliasToBean(Department.class));

criteria.add(Restrictions.isNull("parent.id"));
criteria.add(Restrictions.eq("active", true));
return criteria.list();

那就是说,我认为如果你的意图是返回一个带有子部门树的根部门列表,那么在这里使用投影是一个错误而且是不必要的。为此,您可以这样做:

Criteria criteria = session.createCriteria(Department.class);
criteria.createAlias("children",  "children", JoinType.FULL_JOIN);
criteria.add(Restrictions.isNull("parent.id"));
criteria.add(Restrictions.eq("active", true));

retun criteria.list();