Using Spring JdbcTemplate

1 min read

These examples have been taken (and adapted) from Spring JdbcTemplate.
SELECT
int rowCount = this.jdbcTemplate.queryForObject(
"select count(*) from t_actor", Integer.class);
int countOfActorsNamedJoe = this.jdbcTemplate.queryForObject(
"select count(*) from t_actor where first_name = ?", Integer.class, "Joe");
var id = 123L;
var lastName = this.jdbcTemplate.queryForObject(
"select last_name from t_actor where id = ?",
String.class, id);
var id = 123L;
var sql = "select first_name, last_name from t_actor where id = ?";
var actor = jdbcTemplate.queryForObject(sql, (rs, rowNum) -> {
new Actor(
rs.getString("first_name"),
rs.getString("last_name")
);
}, id);
var sql = "select first_name, last_name from t_actor";
var actors = this.jdbcTemplate.query(sql, (rs, rowNum) -> {
new Actor(
rs.getString("first_name"),
rs.getString("last_name")
);
});
Row Mapper
public List<Actor> findAllActors() {
var sql = "select first_name, last_name from t_actor";
return this.jdbcTemplate.query(sql, actorRowMapper);
}
private final RowMapper<Actor> actorRowMapper = (rs, rowNum) -> {
return new Actor(
rs.getString("first_name"),
rs.getString("last_name")
);
};
INSERT, UPDATE, and DELETE
this.jdbcTemplate.update(
"insert into t_actor (first_name, last_name) values (?, ?)",
"Leonor", "Watling");
this.jdbcTemplate.update(
"update t_actor set last_name = ? where id = ?",
"Banjo", 5276L);
this.jdbcTemplate.update(
"delete from t_actor where id = ?",
Long.valueOf(actorId));
0
Subscribe to my newsletter
Read articles from Deon Slabbert directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Deon Slabbert
Deon Slabbert
I am a fullstack software developer with 35 years experience building enterprise applications for the financial sector and have a passion for learning & teaching others the tools of the trade