Using JdbcTemplate
Spring’s JdbcTemplate
and NamedParameterJdbcTemplate
classes are auto-configured, and you can @Autowire
them directly into your own beans, as shown in the following example:
-
Java
-
Kotlin
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
private final JdbcTemplate jdbcTemplate;
public MyBean(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void doSomething() {
this.jdbcTemplate ...
}
}
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.stereotype.Component
@Component
class MyBean(private val jdbcTemplate: JdbcTemplate) {
fun doSomething() {
jdbcTemplate.execute("delete from customer")
}
}
You can customize some properties of the template by using the spring.jdbc.template.*
properties, as shown in the following example:
-
Properties
-
YAML
spring.jdbc.template.max-rows=500
spring:
jdbc:
template:
max-rows: 500
The NamedParameterJdbcTemplate reuses the same JdbcTemplate instance behind the scenes.
If more than one JdbcTemplate is defined and no primary candidate exists, the NamedParameterJdbcTemplate is not auto-configured.
|