以JDBC的回调函数操作为例:
1、定义一个回调函数接口:用于收集查询结果并转换成实体
import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; public interface ResultSetCall<T> { public List<T> getList(ResultSet resultSet) throws SQLException; }2、定义一个参数回调接口和默认实现类,用于填充参数
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public interface PrepareStatementCall { public PreparedStatement getPrepareStatement(Connection con, String sql, Object[] params) throws SQLException; }
import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class DefaultPrepareStatementCall implements PrepareStatementCall{ @Override public PreparedStatement getPrepareStatement(Connection con, String sql, Object[] params) throws SQLException { CallableStatement pre = con.prepareCall(sql); for(int i=0;i<params.length;i++){ pre.setObject(i+1, params[i]); } return pre; } }
3、调用Dao:
public abstract class BaseDao<T> { protected DataSource dataSource; private PrepareStatementCall call = new DefaultPrepareStatementCall(); public List<T> queryList(String sql, Object[] params, PrepareStatementCall call, ResultSetCall<T> resultSetCall){ Connection con = null; PreparedStatement pre = null; ResultSet set = null; List<T> rs = null; try { con = dataSource.getConnection(); pre = call.getPrepareStatement(con, sql, params); set = pre.executeQuery(); rs = resultSetCall.getList(set); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ this.colseResultSet(set); this.colsePreparedStatement(pre); this.colseConnection(con); } return rs; }4、调用示例:
List<CompleteTask> rs = super.queryList(COMPLETE_NEW_SQL, new Object[]{waybillStatus, eachFetchDataNum}, new ResultSetCall<CompleteTask>(){ @Override public List<CompleteTask> getList(ResultSet set) throws SQLException { List<CompleteTask> rs = new ArrayList<CompleteTask>(); while(set.next()){ CompleteTask task = new CompleteTask(); task.setTaskId(<span style="font-family: Arial, Helvetica, sans-serif;">set.getInt("taskId")</span><span style="font-family: Arial, Helvetica, sans-serif;">);</span> task.setTaskType(<span style="font-family: Arial, Helvetica, sans-serif;">set.getInt("taskType")</span><span style="font-family: Arial, Helvetica, sans-serif;">);</span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>return rs; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>} </span>