1
我寫了一個方法將外部Mysql數據作爲Student DAO複製到我當前的數據庫中。當我在持久層中直接寫入當前數據庫時,我得到的結果是正確的,但是如果我返回一個列表以在邏輯層中使用它,會發生奇怪的事情,並且具有相同名稱的學生的「課程」字段也是相同的它應該是不同的。從Mysql數據庫調用返回列表時出現奇怪的行爲
從數據庫返回列表時,其他人經歷過奇怪的行爲?
這裏是我的代碼:
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;
學生類有一個哈希映射和等於方法嗎?如果不創建它並再次測試。 –
什麼樣的散列表?學生是一個DAO,必須是可序列化 – javanoob
我想你的意思是這樣的:http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java – javanoob