Search code examples
javamysqljdbccollections

How to convert Array (ResultSet JDBC) to List?


I wrote code that should take a record from a database table by record ID. One of the columns of the table (record) is the collection of the student object. How can I pull students out of a record and “fold” it into a List collection?

Code:

public Group findObjById(final int id) {
        Group group = new Group();

        try {
            Statement st = connection.createStatement();
            ResultSet rs = st.executeQuery("SELECT * FROM `course_work`.`group` WHERE `group_id` = " + id + ";");

            while (rs.next()) {
                int innerId = rs.getInt("group_id");
                List<Student> students = rs.getArray("students");
                group = new Group(innerId, students);
            }

            rs.close();
            st.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return group;
    }

There is error on line 10 (102th line in *.java). photo <-

List.copyOf and Arrays.asList DIDNT HELP (because it is not default array).


Solution

  • Try casting the result array to a list like this List<Student> students = (List<Student>) rs.getArray("students");