protected User userFromResultSet(ResultSet rs) { try { User user = User.withUsernameEmailAndLocales( rs.getString("username"), rs.getString("email"), rs.getString("locales")); setUserInternalId(user, rs.getLong("internalId")); setUUId(user, rs.getString("id")); setSalt(user, rs.getString("salt")); setPasswordHash(user, rs.getString("passwordHash")); return user; } catch (SQLException ex) { throw new SQLConnectionException(ex); } }
@Override public void save(User user) { Long id = getInternalId(user); if (id == null) { if (emailExists(user.email())) { throw new ExistingUserException(user.email()); } if (usernameExists(user.username())) { throw new ExistingUserException(user.username()); } // If no user found, this is clearly a new user String query = "insert into member(uuid, salt, username, email, passwordHash, creationTime, updateTime, locales) values(?, ?, ?, ?, ?, ?, ?, ?);"; Timestamp now = new Timestamp(System.currentTimeMillis()); PreparedStatement stm = preparedStatement(query); try { stm.setString(1, user.id()); stm.setString(2, user.salt()); stm.setString(3, user.username()); stm.setString(4, user.email()); stm.setString(5, user.passwordHash()); stm.setTimestamp(6, now); stm.setTimestamp(7, now); stm.setString(8, user.preferredLocales()); stm.executeUpdate(); ResultSet resultSet = stm.getGeneratedKeys(); resultSet.next(); long generatedId = resultSet.getLong(1); setUserInternalId(user, generatedId); } catch (SQLException ex) { throw new SQLConnectionException(ex); } } else { // If a user is found, and if it comes from DB, we can update all its fields String query = "UPDATE member SET salt = ?, passwordHash = ?, updateTime = ?, locales = ? WHERE uuid = ?"; PreparedStatement stm = preparedStatement(query); try { stm.setString(1, user.salt()); stm.setString(2, user.passwordHash()); stm.setTimestamp(3, new Timestamp(System.currentTimeMillis())); stm.setString(4, user.preferredLocales()); stm.setString(5, user.id()); stm.executeUpdate(); } catch (SQLException ex) { throw new SQLConnectionException(ex); } } }