这是另一个问题的相关问题:
Hibernate exception PropertyNotFoundException when using Transformer
我有几个表加入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();
因为我不知道如何用“B”设置相关对象“A”,因为B表中只有一个ID。
请帮忙。非常感谢你。
答案 0 :(得分: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
。这可以合并到您的查询中。在您的select子句中添加b.A
,它应该可以正常工作。
编辑:
如果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
也应该。