DAO层代码重复的很多,可以使用模板方法进行优化
1. 首先再目录下再定义一个包common
2. 再在报下新建接口JDBCCallback
public interface JDBCallback<T> {
T reToObject(ResultSet rs) throws SQLException;
void setParams(PreparedStatement stmt) throws SQLException; //设置参数
}
3. 在包下新建一个抽象类JDBCAbstractCallBack
public abstract class JDBCAbstractCallBack<T> implements JDBCCallBack<T> {
@override
public T reToObject(ResultSet rs){
return null;
};
public setParams(PreparedStatement stmt){
return null;
};
}
4. 再在包下再新建一个类JDBCTemplate1<T>
(采用泛型)
public class JDBCTemplate<T> {
public List<T> query(String sql, JDBCCallback<T> jdbcCallback) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
List<T> data = new ArrayList<T>();
try {
conn = DBUtil.getConnection();
stmt = conn.preparedStatement(sql);
rs = stmt.excuteQuery();
while(rs.next()) {
T object = jdbcCallback.rsToObject(rs);
data.add(object);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(rs, stmt, conn);
}
return data;
}
}
5. 在DAO中调用
JDBCTemplate<Book> jdbcTemlate = new JDBCTemplate<Book>();
jdbcTemlate.query(sql, new JDBCAbstractCallBack<Book>(){
@override
public Book rsToObject(ResultSet rs) throws SQLException {
Book book = new Book();
book.setxxxx(rs.getXXX(xxx));
return book;
}
} );