Java回调函数实例

以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>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值