2015-06-23 123 views
0

我的代碼多次返回對象,但同一個記錄,因爲相同的對象引用正在經歷。請建議進行一些修改,以便獲取所有記錄而不重複相同的行。數據庫中有不同記錄時返回相同的記錄?

DBConnection con = null; 
     List<UserModel> users= new ArrayList<UserModel>(); 
     UserModel userModel = null; 
     try { 
      con = new DBConnection(); 
      LOGGER.info("############### DBUtils.getUsers() start"); 
      ResultSet rs = null; 
      PreparedStatement pstmt = null; 
      pstmt = con.connection.prepareStatement(
        DBUtils.Select.USERS); 
      pstmt.setString(1, user); 
      pstmt.setString(2, pwd); 

      rs = pstmt.executeQuery(); 
      while (rs.next()) { 
       userModel = new UserModel(); 
       userModel.setName(rs.getString("NAME")); 
       userModel.setUserId(rs.getString("USERID")); 
       userModel.setPassword(rs.getString("PASSWORD")); 
       userModel.setAccountDeleted(rs.getString("ACCOUNT_DELETED")); 
       userModel.setAccountEnabled(rs.getString("ACCOUNT_ENABLED")); 
       userModel.setAccountExpired(rs.getString("ACCOUNT_EXPIRED")); 
       userModel.setCreationTime(rs.getString("CREATION_TIME")); 
       userModel.setDeletionTime(rs.getString("DELETION_TIME")); 
       userModel.setCredentialsExpired(rs 
         .getString("CREDENTIALS_EXPIRED")); 
       userModel.setPermissions(rs.getString("PERMISSIONS")); 
       userModel.setLastLoginTime(rs.getString("LAST_LOGIN_TIME")); 
       LOGGER.info("############### DBUtils.getUsers() users : "+userModel); 
       users.add(userModel); 
      } 

      LOGGER.info("############### DBUtils.getUsers() users : "+users); 

     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
     finally{ 
      if(con!= null){ 
       con.closeConnection(); 
      } 
     } 
+0

你可以發佈記錄器 – Madhan

回答

0

創建實例內循環,並將其添加到循環,否則你正在更新相同的參考並將其添加到列表。

while (rs.next()) { 
      UserModel userModel = new UserModel(); 
+2

他已經在做他不是嗎? – Madhan

+0

不,使用相同引用但指向不同對象的OP作爲循環繼續,因此對以前對象的引用將不再使用。 – kosa

+0

Nambari感謝我現在正在獲取數據,並沒有重複的價值....以前我定義UserModel上面沒有裏面,而條件... –

相關問題