我有这两个类:
public class Average {
long id;
String name;
double average;
public Average(long id , String name , double payment)
{
this.id = id;
this.name = name;
this.payment = payment;
}
@Override
public String toString()
{
return id + "\t" + name + " " + payment;
}
}
和
@Entity
public class Payment{
@Id
@GeneratedValue
long id;
Student student;
Subject subject;
double payment;
public Payment()
{
}
我想用java对这个类执行查询,但是它无法正常工作。什么可能是错的。 Bellow我从另一个我称之为的课程中发布了我的查询:
public List<Object> getPayment()
{
Query q = entityManager.createQuery("Select NEW Average( g.subject.id , g.subject.name , AVG(g.payment) ) from Payment g GROUP BY g.subject.id, gge.subject.name");
return q.getResultList();
}
请耐心等待,这是我的第一篇文章!
答案 0 :(得分:2)
Average
不是实体(您应该使用@Entity
对其进行注释 - 就像您为Payment
所做的那样),这样您就无法执行entityManager.createQuery()
。
您还应在@Table(name = "XXX")
之后和课程名称之前指定表@Entity
。
查询应该是这样的:
Select g.subject.id , g.subject.name , AVG(g.payment) from Average a, Payment g GROUP BY g.subject.id, g.subject.name
- 更新
如果Average
是用于投影的Bean类,则执行以下操作:
Object[] payments = (Object[]) entityManager.createQuery("Select g.subject.id,
g.subject.name, AVG(g.payment) from Payment g
GROUP BY g.subject.id, g.subject.name").getSingleResult();
然后迭代payments
:
for (Object object : payments) {
System.out.println(object);
}
如果结果只有一行,则放getSingleResult
,否则你需要List
个对象并遍历列表:
List<Object[]> payments = (List<Object[]>) entityManager.createQuery("Select g.subject.id,
g.subject.name, AVG(g.payment) from Payment g
GROUP BY g.subject.id, g.subject.name").getResultList();
然后迭代payments
:
if (payments != null){
for (Object[] object : payments) {
System.out.println(object[0] + " " + object[1] + " " + object[2]);
}
}
答案 1 :(得分:1)
可能是gge
而不是g
中的GROUP BY g.subject.id, gge.subject.name
吗?