Advanced Features
This article is generated by AI translation.
This section summarizes advanced JdbcTemplate features and knobs:
Log SQL on Error
Set printStmtError to log the SQL statement whenever an error occurs.
- Property: printStmtError
- Default: false
Failed SQL statement [select * from test_user2 where id > 10].
java.sql.SQLSyntaxErrorException: Table 'devtester.test_user2' doesn't exist
... stack trace ...
Surface Database Warnings
Set ignoreWarnings to determine whether SQL warnings raise exceptions.
- Property: ignoreWarnings
- Default: true (warnings ignored)
create table test_table (
id bigint,
name national char(10)
);
NATIONAL/NCHAR/NVARCHAR implies the character set UTF8MB3 ...
Exception in thread "main" java.sql.SQLException: Warning not ignored
... stack trace ...
Query Timeout
Set queryTimeout to a value greater than zero to call Statement.setQueryTimeout.
- Property: queryTimeout
- Default: 0 (disabled)
- Unit: seconds
jdbc.setQueryTimeout(6);
jdbc.queryForList("select * from users");
fetchSize
Set fetchSize to hint how many rows to fetch per round-trip using Statement.setFetchSize.
- Property: fetchSize
- Default: 0 (driver default)
- Unit: rows
jdbc.setFetchSize(256);
jdbc.queryForList("select * from users");
PreparedStatement ps = con.prepareStatement(
"select * from test_user",
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY
);
ps.setFetchSize(Integer.MIN_VALUE);
con.setAutoCommit(false);
PreparedStatement ps = con.prepareStatement(
"select * from test_user",
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY
);
ps.setFetchSize(255);
maxRows
Set maxRows to limit the maximum number of rows returned.
- Property: maxRows
- Default: 0 (no limit)
- Unit: rows
jdbc.setMaxRows(200);
jdbc.queryForList("select * from users");
Some drivers still read the entire result set even if maxRows is reached (e.g., MySQL consumes extra rows but does not expose them).
Dynamic Data Sources
When you cannot supply a DataSource/Connection up front—or each call must use a different source—implement DynamicConnection.
class LocalDynamicConnection implements DynamicConnection {
@Override
public Connection getConnection() throws SQLException {
return ...;
}
@Override
public void releaseConnection(Connection conn) throws SQLException {
...;
}
}
JdbcTemplate jdbc = new JdbcTemplate(new LocalDynamicConnection());
SpringDsAdapter relies on Spring's DataSourceUtils to obtain/release connections so dbVisitor cooperates with Spring's transaction manager. Add: