Skip to main content
Hint

This article is generated by AI translation.

Interface-based Arguments

dbVisitor offers two interface-based ways to pass arguments:

SqlArgSource

The SqlArgSource interface defines common argument access. It can provide values for SQL statements with arguments.

  • ArraySqlArgSource: uses an array as the argument source.
  • BeanSqlArgSource: uses a bean as the argument source.
  • MapSqlArgSource: uses a map as the argument source.
info

Examples below only showcase the capabilities of different SqlArgSource types.

Example 1: ArraySqlArgSource with positional arguments
Object[] array = new Object[] { 2, "Dave"};
SqlArgSource source = new BeanSqlArgSource(array);

jdbcTemplate.queryForList("select * from users where id > ? and name = ?", source);
Example 2: ArraySqlArgSource with named positional arguments
Object[] array = new Object[] { 2, "Dave"};
SqlArgSource source = new BeanSqlArgSource(array);

jdbcTemplate.queryForList("select * from users where id > :arg0 and name = :arg1", source);
Example 3: BeanSqlArgSource passing a bean
User user = new User(2, "Dave");
SqlArgSource source = new BeanSqlArgSource(user);

jdbcTemplate.queryForList("select * from users where id > :id and name = :name", source);
Example 4: MapSqlArgSource passing a map
Map<String, Object> map = Collections.singletonMap("id", 40);
SqlArgSource source = new MapSqlArgSource(map);

jdbcTemplate.queryForList("select * from users where id > :id", source);

PreparedStatement

Use the PreparedStatementSetter interface to set arguments directly on the underlying JDBC PreparedStatement.

warning

When using PreparedStatementSetter, the SQL can only contain ? placeholders; the following are not supported:

  • Named arguments: :name, &name, #{...}
  • SQL injection: ${...}
  • Rules: @{...}
Using PreparedStatement
String sql = "select * from users where id > ?";
jdbcTemplate.queryForList(sql, new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, 2);
}
});