1

I wrote a method to copy external Mysql data into my current database as Student DAOs. When I write to the current database directly in the persistence layer, I get correct results, but if I return a list to use it in the logic layer weird things happen and the "courses" field of Students with the same name is the same where it should be different.

Anyone else has experienced weird behavior when returning lists from a database?

Here is my code:

    List<Student> fetchlist = new ArrayList<Student>();

    try {
        //Connecting to external DB
        Class.forName("com.mysql.jdbc.Driver");
        Connection connect = DriverManager.getConnection(dbstring);

        //GET STUDENTS
        Map<String, Student> studentMap = new HashMap<String, Student>();
        Statement statementStudents = connect.createStatement();
        ResultSet resultSetStudents = statementStudents.executeQuery("select * from students2");

        while (resultSetStudents.next()) {
            Student student = new Student();

            String sid = resultSetStudents.getString("sid");

            String firstname = resultSetStudents.getString("firstname");
            String lastname = resultSetStudents.getString("lastname");
            String email = resultSetStudents.getString("email");

            student.setFirstname(StringEscapeUtils.unescapeHtml(firstname));
            student.setName(StringEscapeUtils.unescapeHtml(lastname));
            student.setEmail(email);

            studentMap.put(sid, student);
        }


        Statement statementBookings = connect.createStatement();
        ResultSet resultSetBookings = statementBookings.executeQuery("select * from bookings2");

        //Go through bookings in order to complete Student and add
        while (resultSetBookings.next()) {
            String cid = resultSetBookings.getString("cid");
            String sid = resultSetBookings.getString("sid");

            String course = "";

                if (cid.equals("1521"))
                    course = "Course 1";
                else if (cid.equals("1522"))
                    course = "Course 2";
                else if (cid.equals("1523"))
                    course = "Course 3";
                else if (cid.equals("1524"))
                    course = "Course 4";

                Student student = studentMap.get(sid);

                student.setCourse(course);

                fetchlist.add(student);

        }
    } catch (ClassNotFoundException e) {
        log.error("Could not find Mysql JDBC class");

    } catch (SQLException e) {
        log.error("Error executing SQL statement");
    }

    return fetchlist;
javanoob
  • 243
  • 1
  • 10

1 Answers1

0

For list-adding I created new Student objects and filled them with the data from the objects from the HashMap. Also I closed all my statements and resultsets where possible. Then I didn't have any wrong data in the list anymore.

javanoob
  • 243
  • 1
  • 10