Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package coderslab.dao;
- import coderslab.entity.User;
- import java.sql.*;
- import java.util.List;
- public class MySqlUserDao implements UserDao{
- private static final String FIND_ALL_USERS =
- "SELECT * FROM users";
- private static final String INSERT_USER_QUERY =
- "INSERT INTO users(name, surname, email, password) " +
- "VALUES (?,?,?,?)";
- private final String jdbcUrl;
- private final String password;
- private final String user;
- public MySqlUserDao(String jdbcUrl, String password, String user) {
- this.jdbcUrl = jdbcUrl;
- this.password = password;
- this.user = user;
- }
- private Connection createConnection() throws SQLException {
- return DriverManager.getConnection(jdbcUrl,user,password);
- }
- @Override
- public User insert(User user) {
- try(Connection connection = createConnection();
- PreparedStatement insertStm =
- connection.prepareStatement(INSERT_USER_QUERY,
- PreparedStatement.RETURN_GENERATED_KEYS)){
- insertStm.setString(1, user.getName());
- insertStm.setString(2, user.getSurname());
- insertStm.setString(3, user.getEmail());
- insertStm.setString(4, user.getPassword());
- int result = insertStm.executeUpdate();
- if(result != 1){
- throw new RuntimeException("Execute updated returned " + result);
- }
- try(ResultSet generatedKeys = insertStm.getGeneratedKeys()){
- if(generatedKeys.first()){
- user.setId(generatedKeys.getInt(1));
- return user;
- }else{
- throw new RuntimeException("Generated key was not found");
- }
- }
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
- @Override
- public List<User> findAll() {
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement