使用Transformers.aliasToBean时检索对象子项

时间:2014-04-09 16:25:57

标签: java sql hibernate

在Hibernate中使用Transformers.aliasToBean函数时,我有一个关于子检索的问题。我已经编写了一个填充我的对象的查询,但是当我尝试填充子项查询时,查询不起作用。我将首先发布示例代码并在下面添加生成的SQL和异常。

public class Parent {
    @Id
    @Column(name="id")
    @GeneratedValue
    private long id;

    @Column(name="name")
    private String name;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name="parent_id")
    @LazyCollection(LazyCollectionOption.FALSE)
    private List<Child> children;

    @Transient
    private long someCount;

    // public constructor + getters and setters

}

public class Child {
    @Id
    @Column(name="id")
    @GeneratedValue
    private long id;

    // public constructor + getters and setters
}

查询

Query query = session.createQuery("SELECT p.id as id, p.name as name, "
    + " (SELECT COUNT(*) FROM stat WHERE parent_id=p.id) as someCount, "
    + " FROM " + Parent.class.getSimpleName() + " p ")                     
.setResultTransformer(Transformers.aliasToBean(Parent.class));

基本上当我尝试在查询的第一行中包含p.children as children时,我得到了hibernate生成的以下sql:

select parent0_.id as col_0_0_, parent0_.name as col_1_0_, . as col_2_0_, 
(select count(*) from stats stat3_ where parent_id=parent0_.id) as col_3_0_, child2_.id 
as id1_2_1_ from inner join child child2_ on parent0_.id=child2_.parent_id

错误是:

WARN: SQL Error: 0, SQLState: 42601
ERROR: ERROR: syntax error at or near "." at position 60

该位置60对应于, . as col_2_0_,查询第一行中点之前的位置。基本上它似乎检索孩子,但生成的SQL阻止它成功执行查询。

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

简单来说,您无法将p.children添加到SELECT的结果列,因为它是一个集合,此处只允许实体或标量。但你可以试试这个替代方案:

Query query = session.createQuery("SELECT p, "
    + " (SELECT COUNT(*) FROM stat WHERE parent_id=p.id) "
    + " FROM " + Parent.class.getSimpleName() + " p " +
    + " LEFT JOIN FETCH p.children ");
for (Object[] row : (List<Object[]>)query.list()) {
    Parent p = (Parent)row[0];
    p.setSomeCount(((Number)row[1]).longValue());
}

请告诉它是否真的适合你。