如何制作方法getUserById

时间:2017-12-17 14:50:23

标签: java methods hashmap

我需要创建一个方法getUserById,它将通过其id返回1个用户。我认为我需要使用HashMap所以这是我的方法:

 public class UserDao {
    private static final String SELECT_USERS = "select * from users_Alana";
    public static List<User> getUsers(JdbcTemplate jdbcTemplate){
        return jdbcTemplate.query(SELECT_USERS,new UserMapper());
    }

    private static class UserMapper implements RowMapper<User> {
        @Nullable
        public User mapRow(ResultSet resultSet, int i) throws SQLException {
            User user = new User();
            user.setId(resultSet.getInt("id"));
            user.setName(resultSet.getString("name"));
            user.setGender(resultSet.getString("gender"));
            user.setAge(resultSet.getInt("age"));
            return user;
        }
    }
    public static void getUserById(int number) throws SQLException {
        HashMap<Integer,User> getUser = new HashMap<Integer, User>();
        if (getUser.containsKey(number)) {
            System.out.println(getUser);
        }
    }
}

我通过UserDao.getUserById(2);在主类中调用此方法。我还有一个类User(具有int id,age; String name,gender;)中的构造函数,getter和setter。
结果什么都没有。怎么解决?

2 个答案:

答案 0 :(得分:2)

您需要从User

返回getUser个对象
public static User getUserById(int number) throws SQLException {
    HashMap<Integer,User> getUser = new HashMap<Integer, User>();
    return getUser.get(number);        
}

您需要使用值

填充HashMap

答案 1 :(得分:2)

要通过ID获取用户,我认为您不需要HashMap,只能使用:

public static void getUserById(int id) throws SQLException {
    UserDao dao = new UserDao();
    List<User> users = dao.getUsers(jdbcTemplate);//This return a List or users
    User user = user.stream()
            .filter(u -> u.getId() == id)// filter the user by id
            .findFirst()// if find then return the first
            .orElseGet(User::new);// else return new User()
}

但最好通过id创建第二个查询来获取用户:

private static final String SELECT_USERS_BY_ID = "select * from users_Alana WHERE id = ?1";