我正在与JPA合作。在执行GROUP BY子句示例时,将引发ClassCastException。
以下是我的代码:
public class StudentGrouping
{
public static void main(String[] args)
{
EntityManager entityManager = EntityManagerUtil.getEmf()
.createEntityManager();
try {
EntityTransaction entr = entityManager.getTransaction();
entr.begin();
Query query = entityManager
.createQuery("SELECT student.studentName, SUM(student.studentAge) FROM Student student GROUP BY student.studentName");
List<?> list = query.getResultList();
Iterator<?> iterator = list.iterator();
while (iterator.hasNext())
{
System.out.println("entered into loop");
Student student = (Student) iterator.next();
System.out.print("Student Name:"+student.getStudentName());
System.out.print(" Age:"+ student.getStudentAge());
System.out.println();
}
entr.commit();
System.out.println("success");
}
catch (Exception e)
{
e.printStackTrace();
} finally {
entityManager.close();
}
}
}
以下是期望:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.demo.entities.Student
at com.demo.action.StudentGrouping.main(StudentGrouping.java:28)
我的POJO类字段是:
@Column(name = "studentName")
private String studentName;
@Column(name = "studentAge")
private int studentAge;
是我的GROUP BY子句查询错误。
最佳答案
这是因为我确定您的Student
类看起来不像
String studentName;
Integer yyyy;
当您要求时得到的是什么
student.studentName, SUM(student.studentAge)
我建议您要么创建一个看起来像您的结果的类,要么将结果视为Object []
如
Object student[] = (Object[])iterator.next();
System.out.print("Student Name:"+student[0]);
System.out.print("Max Age:"+student[1]);