Spring Boot Integration with JdbcClient
Introduction
JdbcClient is a simple wrapper around JdbcTemplate to simplify the usage of JdbcTemplate in Spring Boot applications.
Injections
1 2
| @Autowired private JdbcClient jdbcClient;
|
Entity
1 2 3 4 5 6 7 8 9 10 11 12
| @Entity @Data @NoArgsConstructor @Accessors(chain = true) public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String name; private String email; }
|
RowMapper - map the result set to the entity
1 2 3 4 5 6 7 8 9
| public class CustomerRowMapper implements RowMapper<Customer> { @Override public Customer mapRow(ResultSet rs, int rowNum) throws SQLException { return new Customer() .setId(rs.getLong("id")) .setName(rs.getString("name")) .setEmail(rs.getString("email")); } }
|
Run updates using JdbcClient
You can use positional parameters or named parameters
1 2 3 4 5 6 7 8 9
| jdbcClient.sql("INSERT INTO customer (name, email) VALUES (?, ?)") .param("Alice") .param("alice@def.com") .update();
jdbcClient.sql("INSERT INTO customer (name, email) VALUES (:name, :email)") .param("name", "Bob") .param("email", "bob@def.com") .update();
|
Run Queries using JdbcClient
You can use positional parameters or named parameters in the query. You need to provide a RowMapper to map the result set to the entity.
1 2 3 4 5 6
| List<Customer> customers = jdbcClient .sql("SELECT * FROM customer WHERE id = :customerId") .param("customerId", 1) .query(new CustomerRowMapper()) .list(); customers.forEach(System.out::println);
|