0

这是与另一个问题相关的问题:

使用 Transformer 时出现休眠异常 PropertyNotFoundException

我有几张表加入 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;

    // 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;

    @Transient
    private Double length;

    @Transient
    private String unit;

    // 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
    ...
}

解决了这个问题后,现在是这样的:

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

现在的问题是:

我不知道如何在 HQL 中返回的 B 对象中设置 A 的别名。当我这样做时,这会导致 NPE:

b.getA().getName();

因为我不知道如何将相关对象“A”设置为“B”,因为B表中只有一个ID。

请帮忙。非常感谢你。

4

1 回答 1

1

b.getA().getName();这将引发 NPE,因为select b.id as id, sum(c.length) as length, min(c.unit) as unit from B b不包括A. 当您在 HQL 查询中使用 select 子句时,它只会返回提到的字段。

请参阅http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html了解更多信息。

编辑:

如果您通读提供的文档,您会看到select cat.mate from Cat cat. 这可以合并到您的查询中。添加b.A您的 select 子句,它应该可以工作。

编辑:

如果select b.id as id, sum(c.length) as length, min(c.unit) as unit from B b left outer join b.c as c group by b.id 工作那么 select b.id as id, sum(c.length) as length, min(c.unit) as unit, b.A from B b left outer join b.c as c group by b.id, b.A 也应该。

于 2012-12-13T08:43:26.440 回答