Skip to main content
Hint

This article is generated by AI translation.

Programmatic API

The programmatic API is based on the core JdbcTemplate class, providing database access centered on raw SQL. It is the most low-level and flexible data-access approach in dbVisitor, best suited for scenarios requiring full control over SQL.

Highlights
  • Write SQL directly — ideal for complex queries, JOINs, subqueries, window functions, etc.
  • Supports positional parameters ?, named parameters :name / #{name}, and PreparedStatementSetter for parameter binding.
  • Multiple result-set handling options: map to Bean, Map, single value, or custom RowMapper.
  • Built-in batch operations executeBatch and stored-procedure calls call.
  • JdbcTemplate is stateless — create and discard at will.

Create

Create from DataSource or Connection
DataSource dataSource = ...
JdbcTemplate jdbc = new JdbcTemplate(dataSource);

Or

Connection conn = ...
JdbcTemplate jdbc = new JdbcTemplate(conn);

Insert / Update / Delete

Execute DDL / DML statements
// DDL
jdbc.execute("create table user_info (id int primary key, name varchar(50))");

// Raw SQL
jdbc.executeUpdate("insert into user_info (id,name) values (1, 'Bob')");

// Positional parameters (?)
jdbc.executeUpdate("insert into user_info (id,name) values (?,?)",
new Object[] { 2, "Alice" });

// Named parameters (:name)
Map<String, Object> params = CollectionUtils.asMap("id", 3, "name", "David");
jdbc.executeUpdate("insert into user_info (id,name) values (:id, :name)", params);

Query

Multiple query styles
// Map to Bean
List<User> users = jdbc.queryForList("select * from user_info", User.class);

// Map to Map
List<Map<String, Object>> maps = jdbc.queryForList("select * from user_info");

// Single value
Long total = jdbc.queryForObject("select count(*) from user_info", Long.class);

// Custom RowMapper (net.hasor.dbvisitor.jdbc.RowMapper)
List<String> names = jdbc.queryForList("select * from user_info",
(rs, rowNum) -> rs.getString("name").toUpperCase());

Batch Operations

Batch insert / update
String sql = "insert into user_info (id,name) values (?,?)";
Object[][] batchArgs = {
{ 1, "Alice" },
{ 2, "Bob" },
{ 3, "Carol" }
};
int[] results = jdbc.executeBatch(sql, batchArgs);

Stored Procedures

Call a stored procedure (with INOUT parameter)
Map<String, Object> result = jdbc.call(
"CALL sp_add_numbers(?, ?, ?)",
new Object[] { 10, 5, SqlArg.asInOut("result", 0, java.sql.Types.INTEGER) }
);
// result.get("result") → 15
For more on the Programmatic API, see: