如果DB中有不同的记录,则返回相同的记录?

时间:2015-06-23 15:57:35

标签: java java-ee servlets jdbc

我的代码返回对象但多次返回相同的记录,因为同一个对象引用正在经历。请建议一些修改,以便我获得所有记录而不重复相同的行。

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();
            }
        }

1 个答案:

答案 0 :(得分:0)

在循环内创建实例并将其添加到循环中,否则您将更新相同的引用并将其添加到列表中。

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