5.1 Programmatic API
JdbcTemplate is a database operation wrapper designed by dbVisitor specifically for SQL string scenarios. It is stateless and can be created and destroyed at any time.
Start by Scenario
| Goal | Entry |
|---|---|
| Run an existing SQL query | Queries |
| Execute INSERT, UPDATE, DELETE, or DDL | Updates |
| Submit many argument sets or many SQL statements | Batches |
| Call stored procedures or functions | Stored Procedure Calls |
| SQL returns multiple result sets | Multiple Results |
| Work directly with Connection or Statement | Template Methods |
Creation and Usage
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
// Query
List<Map<String, Object>> rows = jdbc.queryForList("select * from users where age > ?", 18);
// Update
int affected = jdbc.executeUpdate("update users set name = ? where id = ?", new Object[] { "alice", 1 });
Hint
How you obtain JdbcTemplate depends on your project architecture. See Framework Integration for details.
Principle
JdbcTemplate is based on the Template pattern. Inside the template method, it automatically handles acquiring connections, releasing connections, and catching exceptions. Higher-level code only needs to focus on using the Connection.
Core Template Method
T result = jdbc.execute((ConnectionCallback<T>) con -> {
// Use Connection directly
});
User Guide
- Query, execute SELECT or other statements with return results.
- Update, execute INSERT, UPDATE, DELETE, or DDL.
- Batch, execute batch operations.
- Stored Procedure, call stored procedures/functions.
- Rules, use rules to give SQL dynamic capabilities.
- Multi-value, execute SQL with multiple statements and obtain all results.
- Script, execute SQL script files or multiple statements.
- Using Template, operate the database directly via template methods.
- Advanced Features, JdbcTemplate-specific properties and features.
- Arguments, learn about different ways to pass arguments.
- Receiving Results, learn about different ways to receive results.