이전에 했던 프로젝트를 DataSource, 익명클래스로 리팩토링하여 기존의 코드를 좀 더 간단히 출력하고 중복코드를 줄일 수 있도록 함
이전 프로젝트 : https://velog.io/@qowl880/Spring-Spring%EC%97%90%EC%84%9C-Query%EB%AC%B8-%EB%A6%AC%ED%8C%A9%ED%86%A0%EB%A7%812
Factory
@Bean
public UserDao awsUserDao() {
UserDao userDao = new UserDao(awsdataSource());
return userDao;
}
@Bean
DataSource awsdataSource() {
Map<String, String> env = System.getenv();
SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
dataSource.setDriverClass(com.mysql.cj.jdbc.Driver.class);
dataSource.setUrl(env.get("DB_HOST"));
dataSource.setUsername(env.get("DB_USER"));
dataSource.setPassword(env.get("DB_PASSWORD"));
return dataSource;
}
DAO
public class UserDao {
private DataSource dataSource;//ConnectionMaker connectionMaker;
public UserDao(DataSource dataSource) {
this.dataSource = dataSource;
}
// public UserDao(ConnectionMaker connectionMaker) {
// this.connectionMaker = connectionMaker;}
public User select(String id) throws SQLException {
Connection c = dataSource.getConnection();//connectionMaker.makeConnection();
PreparedStatement ps = c.prepareStatement("SELECT * FROM users where id =?");
ps.setString(1, id);
ResultSet rs = ps.executeQuery();
rs.next();
User user = new User(rs.getString("id"), rs.getString("name"), rs.getString("password"));
rs.close();
ps.close();
c.close();
return user;
}//기존 ConnectionMaker부분을 dataSource로 의존관계를 바꾼다
}
new 인터페이스이름() {클래스 본문};
public void deleteAll() throws SQLException {
// "delete from users"
jdbcContextWithStatementStrategy(new StatementStrategy() {
@Override
public PreparedStatement makeStatement(Connection conn) throws SQLException {
return conn.prepa reStatement("delete from users");
}
});
}
public void add(final User user) throws SQLException {
// DB접속 (ex sql workbeanch실행)
jdbcContextWithStatementStrategy(new StatementStrategy() {
@Override
public PreparedStatement makeStatement(Connection conn) throws SQLException {
PreparedStatement pstmt = null;
pstmt = conn.prepareStatement("INSERT INTO users(id, name, password) VALUES(?,?,?);");
pstmt.setString(1, user.getId());
pstmt.setString(2, user.getName());
pstmt.setString(3, user.getPassword());
return pstmt;
}
});
}
public class JdbcContext {
private DataSource dataSource;
public JdbcContext(DataSource dataSource) {
this.dataSource = dataSource;
}
public void workWithStatementStrategy(StatementStrategy stmt) throws SQLException {
Connection c = null;
PreparedStatement pstmt = null;
try {
c = dataSource.getConnection();
pstmt = stmt.makeStatement(c);
// Query문 실행
pstmt.executeUpdate();
} catch (SQLException e) {
throw e;
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
}
}
if (c != null) {
try {
c.close();
} catch (SQLException e) {
}
}
}
}
}
add메서드만 구현(Delete도 똑같이 구현하면 됨)
public class UserDao {
private final DataSource dataSource;
private final JdbcContext jdbcContext;
public UserDao(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcContext = new JdbcContext(dataSource);
}
public void add(final User user) throws SQLException {
// DB접속 (ex sql workbeanch실행)
jdbcContext.workWithStatementStrategy(new StatementStrategy() {
@Override
public PreparedStatement makeStatement(Connection conn) throws SQLException {
PreparedStatement pstmt = null;
pstmt = conn.prepareStatement("INSERT INTO users(id, name, password) VALUES(?,?,?);");
pstmt.setString(1, user.getId());
pstmt.setString(2, user.getName());
pstmt.setString(3, user.getPassword());
return pstmt;
}
});
}
JdbcContext파일에 넣음
public void executeSql(String sql) throws SQLException {
this.workWithStatementStrategy(new StatementStrategy() {
@Override
public PreparedStatement makePreparedStatement(Connection connection) throws SQLException {
return connection.prepareStatement(sql);
}
});
}
DAO(Delete)
public void deleteAll() throws SQLException {
this.jdbcContext.executeSql("delete from users");
}