Java回调函数实例

以JDBC的回调函数操作为例:

1、定义一个回调函数接口:用于收集查询结果并转换成实体

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public interface ResultSetCall {

	public List 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

3、调用Dao:

public abstract class BaseDao {

	protected DataSource dataSource;
	private PrepareStatementCall call = new DefaultPrepareStatementCall();
	public List queryList(String sql, Object[] params, PrepareStatementCall call, ResultSetCall resultSetCall){
		Connection con = null;
		PreparedStatement pre = null;
		ResultSet set = null;
		List 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 rs = super.queryList(COMPLETE_NEW_SQL, new Object[]{waybillStatus, eachFetchDataNum}, new ResultSetCall(){
			@Override
			public List getList(ResultSet set) throws SQLException {
				List rs = new ArrayList();
				while(set.next()){
					CompleteTask task = new CompleteTask();
					task.setTaskId(set.getInt("taskId"));
					task.setTaskType(set.getInt("taskType"));
								}
								return rs;
						}
					}




你可能感兴趣的:(Java回调函数实例)