This is a related question to another question:
Hibernate exception PropertyNotFoundException when using Transformer
I have several tables joining hql. The tables are like this:
A
- A_ID
- NAME
B
- B_ID
- A_ID
C
- C_ID
- B_ID
- LENGTH
- UNIT
Classes:
@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
...
}
After solving that issue, it is like this now:
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
Now the problem is:
I don’t know how to set the alias of A in the returned B object in the HQL. This is causing a NPE when I’m doing this:
b.getA().getName();
Because I don’t know how to set the related object “A” with “B” since there is only an ID in the B table.
Please help. Thank you very much.
b.getA().getName();This will throw a NPE becauseselect b.id as id, sum(c.length) as length, min(c.unit) as unit from B bdoes not includeA. When you use the select clause in a HQL query it will only return the fields mentioned.Please refer to http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html for more information.
EDIT:
If you read through the documentation provided you would have see
select cat.mate from Cat cat. This can be incorporated to your query. Addb.Ain your select clause and it should work.EDIT:
If
select b.id as id, sum(c.length) as length, min(c.unit) as unitfrom B b
left outer join b.c as c
group by b.id
work then
select b.id as id, sum(c.length) as length, min(c.unit) as unit, b.Afrom B b
left outer join b.c as c
group by b.id, b.A
should as well.