JdbcTemplate中的ConnectionCallback和PreparedStatementCallback有什么区别?

ConnectionCallback和PreparedStatementCallback都是JdbcTemplate用于执行自定义SQL操作的接口。

主要区别如下:

ConnectionCallback:

  • 实现ConnectionCallback接口,可以获取Connection对象
  • 可以执行任意SQL操作,包括查询、更新、调用存储过程等
  • 示例:
public class UserConnectionCallback implements ConnectionCallback<List<User>> {
    public List<User> doInConnection(Connection conn) throws SQLException {
        PreparedStatement ps = conn.prepareStatement("SELECT * FROM user");
        ResultSet rs = ps.executeQuery();
        List<User> users = ...;  // 从rs中解析用户列表
        return users;
    }
}

List<User> users = jdbcTemplate.execute(new UserConnectionCallback());

PreparedStatementCallback:

  • 实现PreparedStatementCallback接口,可以获取PreparedStatement对象
  • 只能执行查询和更新操作
  • 示例:
public class UserPreparedStatementCallback implements PreparedStatementCallback<List<User>> {  
    public List<User> doInPreparedStatement(PreparedStatement ps) throws SQLException {
        ps.setInt(1, 10);
        ResultSet rs = ps.executeQuery();
        List<User> users = ...;  // 从rs中解析用户列表
        return users; 
    }
}  

List<User> users = jdbcTemplate.execute(sql, new UserPreparedStatementCallback());   
  • 传入SQL语句,会创建PreparedStatement,然后调用回调方法

所以,主要区别在于能获取的对象:
ConnectionCallback:Connection对象,可以任意操作
PreparedStatementCallback:PreparedStatement对象,较为受限

相比而言:
ConnectionCallback:
优点:操作更加灵活
缺点:需要自己创建PreparedStatement,稍显繁琐
PreparedStatementCallback:
优点:简单,直接获取PreparedStatement
缺点:只能执行查询和更新

具体选择哪种方式,依赖于SQL操作的复杂度,简单的查询更新使用PreparedStatementCallback,复杂操作使用ConnectionCallback,它们使自定义SQL执行变得简单,不再需要手动获取Connection或PreparedStatement。