class UserDAO
public User findByUserId(String userId) throws SQLException {
SelectJdbcTemplate template =new SelectJdbcTemplate() {
@Override
public void setParameters(PreparedStatement pstmt) throws SQLException {
pstmt.setString(1, userId);
}
@Override
public Object mapRow(ResultSet rs) throws SQLException {
if (!rs.next()) {
return null;
}
return new User(
rs.getString("userId"),
rs.getString("password"),
rs.getString("name"),
rs.getString("email"));
}
};
String sql = "select * from USERS where userId = ?";
return (User)template.executeQuery(sql);
}
class SelectJdbcTemplate
package net.slipp.support;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.slipp.user.User;
public abstract class SelectJdbcTemplate {
public Object executeQuery(String sql) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = ConnectionManager.getConnection();
pstmt = conn.prepareStatement(sql);
setParameters( pstmt);
rs = pstmt.executeQuery();
return mapRow(rs);
} finally {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
}
public abstract void setParameters(PreparedStatement pstmt) throws SQLException ;
public abstract Object mapRow(ResultSet rs) throws SQLException ;
}
ctrl + alt +m
댓글 ( 4)
댓글 남기기