Template Methods
dbVisitor supports the following template method usage patterns:
Get a Connection
ConnectionCallback gives you direct access to java.sql.Connection. JdbcTemplate acquires/releases the connection and handles exceptions.
T resultList = jdbcTemplate.execute((ConnectionCallback<T>) con -> {
return ...;
});
Get a Statement
StatementCallback exposes java.sql.Statement. JdbcTemplate manages connection acquisition, statement creation/closure, and exception handling.
T resultList = jdbcTemplate.execute((StatementCallback<T>) stmt -> {
return ...;
});
Custom PreparedStatement Setup
Template methods let you customize PreparedStatement creation.
- Set arguments, read results via ResultSetExtractor
T result = jdbc.executeCreator(con -> {PreparedStatement ps = con.prepareStatement("select * from users where id > ?");ps.setInt(1, 2);return ps;}, (ResultSetExtractor) rs -> {return ...;});
- Set arguments, read results via RowMapper
List<User> result = jdbc.executeCreator(con -> {PreparedStatement ps = con.prepareStatement("select * from users where id > ?");ps.setInt(1, 2);return ps;}, (RowMapper<User>) (rs, rowNum) -> {return ...;});
- Set arguments, process rows via RowCallbackHandler
jdbc.executeCreator(con -> {PreparedStatement ps = con.prepareStatement("select * from users where id > ?");ps.setInt(1, 2);return ps;}, (RowCallbackHandler) (rs, rowNum) -> {// process one row});
Call Stored Procedures
List<Object> objectMap = new JdbcTemplate(conn).call("{call proc_select_table(?,?)}", cs -> {
cs.setString(1, "dative");
cs.registerOutParameter(2, Types.VARCHAR);
}, cs -> {
// Receive all results using MultipleResultSetExtractor
List<Object> objects = new MultipleResultSetExtractor().doInCallableStatement(cs);
// Get output parameter
objects.add(cs.getString(2));
return objects;
});