2

我正在使用 hibernate 和 hql 来查询我的 Java 代码。但我有一个这样的例外:

Caused by: org.hibernate.PropertyNotFoundException: Could not find setter for 0 on class [my class]
    at org.hibernate.property.ChainedPropertyAccessor.getSetter(ChainedPropertyAccessor.java:44)

我不明白“0”是什么意思。以下是一些带有示例的详细信息:

我有几张表加入 hql。表格是这样的:

A
- A_ID
- NAME

B
- B_ID
- A_ID

C
- C_ID
- B_ID
- LENGTH
- UNIT

课程:

@Entity
@Table(name="A")
class A
{
    @Id
    @Column(name="A_ID", updatable=false)
    private Long id;

    @Column(name="NAME", nullable=false, length=10, updatable=false)
    private String name;

    @OneToMany(mappedBy="a", fetch=FetchType.LAZY, cascade={CascadeType.ALL})
    @JoinColumn(name="A_ID", nullable=false)
    private Set<B> bs;

    @Transient
    private Double length;

    @Transient
    private String unit;

    // Setters and getters
    ...
}

@Entity
@Table(name="B")
class B
{
    @Id
    @Column(name="B_ID", updatable=false)
    private Long id;

    @ManyToOne
    @JoinColumn(name="A_ID", nullable=false, insertable=true, updatable=false)
    private A a;

    @OneToMany(mappedBy="b", fetch=FetchType.LAZY, cascade={CascadeType.ALL})
    @JoinColumn(name="B_ID", nullable=false)
    private Set<C> cs;

    // Setters and getters
    ...
}

@Entity
@Table(name="C")
class C
{
    @Id
    @Column(name="C_ID", updatable=false)
    private Long id;

    @ManyToOne
    @JoinColumn(name="B_ID", nullable=false, insertable=true, updatable=false)
    private B b;

    @Column(name="LENGTH", nullable=false, updatable=false)
    private Double length;

    @Column(name="UNIT", nullable=false, length=10, updatable=false)
    private String unit;

    // Setters and getters
    ...
}

hql:

select a, sum(c.length) as length, min(c.unit) as unit
from A a
left outer join a.b as b
left outer join b.c as c
group by
a.id
a.name

询问:

Query query = session.createQuery(hql.toString()).setResultTransformer(Transformers.aliasToBean(A.class));

结果是对象“A”的列表,其中包含收集的长度和单位。我不明白为什么我得到这个例外。请给一些建议。


更新:

我写了一个 ResultTransformer 并输出所有的“别名”来查看问题:

-> 0
-> length
-> unit

似乎除了长度和单位之外,它还对待“A”。我的 HQL 应该有问题吗?

4

2 回答 2

10

发现问题:

即使HQL可以正确翻译成sql,但是当ResultTransformer得到结果时,结果中只会有3个字段:

1. A
2. length
3. unit

无论 A 中有多少个字段,它们都将被聚合到一个字段“A”中,由于我没有为该字段设置任何别名,因此将其视为“字段 0”。

因此,在我像这样更改 HQL 后问题解决了:

select a.id as id, a.name as name, sum(c.length) as length, min(c.unit) as unit
from A a
left outer join a.b as b
left outer join b.c as c
group by
a.id
a.name
于 2012-12-12T09:53:39.160 回答
0

@Access(AccessType.FIELD)

添加每个字段的getter和setter

 @Entity
    @Table(name="A")
    @Access(AccessType.FIELD)
    class A
    {
        @Id
        @Column(name="A_ID", updatable=false)
        private Long id;

       public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id= id;
    }
}
于 2012-12-12T07:26:24.197 回答