1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| package com.prvi.gabriel.springbootforjdbctemplate.repository;
import com.prvi.gabriel.springbootforjdbctemplate.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository;
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List;
@Repository public class UserRepositoryImpl implements UserRepository {
@Autowired private JdbcTemplate jdbcTemplate;
@Override public List<User> findUsers() { return jdbcTemplate.query("select * from users",new UserMapper()); }
@Override public User findUserById(long id) { List<User> users = jdbcTemplate.query("select * from users where id = ?",new Object[]{id},new UserMapper()); User user = null; if(users != null&&!users.isEmpty()){ user = users.get(0); } return user; }
@Override public int saveUser(User user) { return jdbcTemplate.update("insert into users (username,password) values (?,?)",new Object[]{user.getUsername(),user.getPassword()}); }
@Override public int delUserById(long id) { return jdbcTemplate.update("delete from users where id = ?",new Object[]{id}); }
@Override public int updateUser(User user) { return jdbcTemplate.update("update users set username = ? , password = ? where id = ?",new Object[]{user.getUsername(),user.getPassword(),user.getId()}); } }
class UserMapper implements RowMapper<User>{
@Override public User mapRow(ResultSet resultSet, int i) throws SQLException { User user = new User(); user.setId(resultSet.getLong("id")); user.setUsername(resultSet.getString("username")); user.setPassword(resultSet.getString("password")); return user; } }
|