简体   繁体   中英

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:

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 . 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 . Then I use the student_ids to select all Students from the Student table. In other words I want to collect all Students in an ArrayList<Student> , who are in the given 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 . The System.out.println(studentsInCourse); returns [[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> ?

Try to give the classname you expect as the second argument of your createNativeQuery call:

studentsInCourse = em
            .createNativeQuery(
                    "SELECT * FROM Student WHERE id IN (SELECT student_id FROM CourseResult WHERE course_id = ?)", Student.class)
            .setParameter(1, course.getId()).getResultList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM