[英]Native Query returns list with java.lang.Object instead of custom object type in JPA application
I have the following tables in my MySQL database: 我的MySQL数据库中有以下表格:
Student
id | firstName | lastName | ...
Course
id | name | cp | ...
-
CourseResult (course_id and student_id are created by JPA)
id | course_id | student_id | grade | ...
-
I am trying to work with all Students
who are in a Course
defined by a given course_id
. 我正在尝试与所有在给定course_id
定义的Course
Students
course_id
。 For that I've created a method in my controller: 为此,我在控制器中创建了一个方法:
public String showCourseResultList(Course course) {
this.course = course;
studentsInCourse = new ArrayList<Student>();
studentsInCourse = em
.createNativeQuery(
"SELECT * FROM Student WHERE id IN (SELECT student_id FROM CourseResult WHERE course_id = ?)")
.setParameter(1, course.getId()).getResultList();
System.out.println(studentsInCourse);
return "courseResultList?faces-redirect=true";
}
So in the NativeQuery I am detecting all student_ids
for a given course_id
. 所以在NativeQuery中,我正在检测给定course_id
所有student_ids
。 Then I use the student_ids
to select all Students
from the Student
table. 然后我用student_ids
选择所有Students
从Student
表。 In other words I want to collect all Students
in an ArrayList<Student>
, who are in the given Course
. 换句话说,我要收集所有Students
在一个ArrayList<Student>
,谁在给定的Course
。
The problem is, that after doing that, the ArrayList<T>
contains elements from the type java.lang.Object
instead of my custom type Student
. 问题是,这样做之后, ArrayList<T>
包含来自java.lang.Object
类型的元素,而不是我的自定义类型Student
。 The System.out.println(studentsInCourse);
System.out.println(studentsInCourse);
returns [[Ljava.lang.Object;@3adaf419, [Ljava.lang.Object;@7ccfb37e]
. 返回[[Ljava.lang.Object;@3adaf419, [Ljava.lang.Object;@7ccfb37e]
。
How can I collect all the Students
from type Student
in my ArrayList<T>
instead of ArrayList<java.lang.Object>
? 我怎么能收集所有的Students
从类型Student
在我ArrayList<T>
代替ArrayList<java.lang.Object>
?
Try to give the classname you expect as the second argument of your createNativeQuery call: 尝试给您期望的类名作为createNativeQuery调用的第二个参数:
studentsInCourse = em
.createNativeQuery(
"SELECT * FROM Student WHERE id IN (SELECT student_id FROM CourseResult WHERE course_id = ?)", Student.class)
.setParameter(1, course.getId()).getResultList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.