Spring JdbcTemplate中的回调

来源:互联网 发布:西建大导师知乎 编辑:程序博客网 时间:2024/06/06 02:27

回调

JdbcTemplate类支持的回调类:

1.预编译语句及存储过程创建回调:用于根据JdbcTemplate提供的连接创建相应的语句;

1.1 PreparedStatementCreator

<T> T execute(PreparedStatementCreator psc, PreparedStatementCallback<T> action)

PreparedStatementCreator:通过回调获取JdbcTemplate提供的Connection,由用户使用该Conncetion创建相关的PreparedStatement;

Integer count = jdbcTemplate.execute(                new PreparedStatementCreator() {                    @Override                    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {                        return con.prepareStatement("SELECT count(1) FROM student");//**拓展点1,改写sql                    }                },                new PreparedStatementCallback<Integer>() {                    @Override                    public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {                        ResultSet resultSet = ps.executeQuery();                        resultSet.next();                        return resultSet.getInt(1);//**拓展点2,改写返回值                    }                });

1.2 PreparedStatementCreator 处理存储过程

2.预编译语句设值回调:用于给预编译语句相应参数设值;

2.1 PreparedStatementSetter:

public int update(String sql, PreparedStatementSetter pss) throws DataAccessException

通过回调获取JdbcTemplate提供的PreparedStatement,由用户来对相应的预编译语句相应参数设值;

jdbcTemplate.update("INSERT INTO student(id,name) VALUES (?,?)", new PreparedStatementSetter() {            @Override            public void setValues(PreparedStatement ps) throws SQLException {                ps.setInt(1, 11);                ps.setString(2, "小张");            }});

此拓展点可以设置SQL的参数值

2.2BatchPreparedStatementSetter:;

类似于PreparedStatementSetter,但用于批处理,需要指定批处理大小;

自定义功能回调:提供给用户一个扩展点,用户可以在指定类型的扩展点执行任何数量需要的操作;

     ConnectionCallback:通过回调获取JdbcTemplate提供的Connection,用户可在该Connection执行任何数量的操作;     StatementCallback:通过回调获取JdbcTemplate提供的Statement,用户可以在该Statement执行任何数量的操作;     PreparedStatementCallback:通过回调获取JdbcTemplate提供的PreparedStatement,用户可以在该PreparedStatement执行任何数量的操作;     CallableStatementCallback:通过回调获取JdbcTemplate提供的CallableStatement,用户可以在该CallableStatement执行任何数量的操作;

结果集处理回调:通过回调处理ResultSet或将ResultSet转换为需要的形式;

     RowMapper:用于将结果集每行数据转换为需要的类型,用户需实现方法mapRow(ResultSet rs, int rowNum)来完成将每行数据转换为相应的类型。     RowCallbackHandler:用于处理ResultSet的每一行结果,用户需实现方法processRow(ResultSet rs)来完成处理,在该回调方法中无需执行rs.next(),该操作由JdbcTemplate来执行,用户只需按行获取数据然后处理即可。     ResultSetExtractor:用于结果集数据提取,用户需实现方法extractData(ResultSet rs)来处理结果集,用户必须处理整个结果集;
原创粉丝点击