역시 개발은 12시 이후에 해야 되나보다.... 그래서 60세이후론 힘듬...ㅋㅋ
CSDN을 참고로 DAO 패턴을 작성했다. 역시 좋은 자료가 많음...
먼저 BaseDAO이다.
아직 완성된 것은 아니지만, 목록은 나온다. 원작에서는 ioc 까지 구현했지만, 자바 기본에선 일단 이정도면 되겠다.
완벽히 이해하려면 자바 리플렉션과 제네릭스를 이해해야하지만,,
다음은 이 BaseDAO를 상속받은 EmpDAO이다.
그리고 테스트를 진행한 서블릿이다.
개발툴은 자바 11(1.8)과 톰캣 8.5 그리고 인텔리제이 ultimate 이다.
package com.sora.webapptest;
import com.sora.webapptest.dao.EmployeeDAO;
import com.sora.webapptest.dto.Employee;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet(name = "EmpServlet", value = "/EmpServlet")
public class EmpServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
EmployeeDAO dao = new EmployeeDAO();
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
List<Employee> employeeList = dao.getEmpList();
out.println("<html><head><title>emp list</title></head><body>");
out.println("<ul>");
for (Employee employee : employeeList) {
out.println("<li>" + employee.getEmployee_id() + " " + employee.getFirst_name() + "</li>");
}
out.println("</ul>");
out.println("</body></html>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
package com.sora.webapptest.dao;
import com.sora.webapptest.basedao.BaseDAO;
import com.sora.webapptest.dto.Employee;
import java.util.List;
public class EmployeeDAO extends BaseDAO<Employee> {
public List<Employee> getEmpList() {
String sql = "select employee_id, first_name, last_name from employees";
return executeQuery(sql, (Object[]) null);
}
}
package com.sora.webapptest.basedao;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public abstract class BaseDAO<T> {
public final String DRIVER = "oracle.jdbc.OracleDriver";
public final String URL = "jdbc:oracle:thin:@localhost:1521:java";
public final String USER = "hr";
public final String PWD = "hr";
protected Connection conn;
protected PreparedStatement pstmt;
protected ResultSet rs;
private Class entityClass;
public BaseDAO() {
Type genericType = getClass().getGenericSuperclass();
Type[] actualTypeArguments = ((ParameterizedType) genericType).getActualTypeArguments();
Type actualType = actualTypeArguments[0];
try {
entityClass = Class.forName(actualType.getTypeName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
protected Connection getConn() {
try {
//1.
Class.forName(DRIVER);
return DriverManager.getConnection(URL, USER, PWD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return null;
}
protected void close(ResultSet rs, PreparedStatement pstmt, Connection conn) {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void setParams(PreparedStatement pstmt, Object... params) throws SQLException {
if (params != null && params.length > 0) {
for (int i=0; i<params.length; i++) {
pstmt.setObject(i+1, params[i]);
}
}
}
private void setValue(Object obj, String property, Object propertyValue) {
Class clazz = obj.getClass();
try {
Field field = clazz.getDeclaredField(property.toLowerCase());
field.setAccessible(true);
field.set(obj, propertyValue);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
protected List<T> executeQuery(String sql, Object... params) {
List<T> list = new ArrayList<>();
try {
conn = getConn();
pstmt = conn.prepareStatement(sql);
setParams(pstmt, params);
rs = pstmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
while (rs.next()) {
T entity = (T)entityClass.newInstance();
for(int i=0; i<columnCount; i++) {
String columnName = rsmd.getColumnName(i+1);
Object columnValue = rs.getObject(i+1);
setValue(entity, columnName, columnValue);
}
list.add(entity);
}
} catch (SQLException | InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
} finally {
close(rs, pstmt, conn);
}
return list;
}
}
'JAVA' 카테고리의 다른 글
| Dao JDBC #3 (0) | 2023.01.18 |
|---|---|
| DAO JDBC #2 (0) | 2023.01.18 |
| Servletでいまの時間を表示する (0) | 2023.01.01 |
| IntellijでTomcat8.5を連携するときに不具合発生 (0) | 2023.01.01 |
| tomcat 8.0.x 설치 (0) | 2022.12.31 |
