【SpringBoot初级篇】JdbcTemplate常用方法
| 函数 | 场景说明 |
|---|---|
| update(String sql, @Nullable Object… args) | 增,删,改 |
| queryForObject(sql, Integer.class) | 查询返回某个值 |
| queryForObject(sql, new BeanPropertyRowMapper<>(User.class), 1) | 查询返回的是某个对象、BeanPropertyRowMapper返回自定义对象 |
| query(sql, new BeanPropertyRowMapper<>(User.class)) | 查询返回的是某个集合 |
| queryForMap(sql) | 查询返回的是map |
业务开发中输出sql日志
logging:
level:
org.springframework.jdbc.core.JdbcTemplate: debug
JdbcTemplate 查询
1、查询记录条数
String sql = "select count(*) from tb_user";
int count = jdbcTemplate.queryForObject(sql, Integer.class);
2、按条件查询记录条数,通过?参数绑定
String sql = "select count(*) from tb_user where username = ?";
int count = jdbcTemplate.queryForObject(sql, Integer.class, "Tom");
或者
String sql = "select count(*) from tb_user where username = ?";
Object[] params = new Object[]{
"Tom"};
int count = jdbcTemplate.queryForObject(sql, params, Integer.class);
3、查询多个字段,返回一个Map
String sql = "select user_id, username, age from tb_user where user_id = ?";
Object[] params = new Object[]{
"46a8247fbffc46c3a591961351fa3277"};
Map<String, Object> resultMap = jdbcTemplate.queryForMap(sql, params);
4、查询多条数据,每条数据都以Map形式返回,整个结果是List<Map<String, Object>>
String sql = "select user_id, username, age from tb_user where age = ?";
Object[] params = new Object[]{
25};
List<Map<String, Object>> resultMapList = jdbcTemplate.queryForList(sql, params);
5、查询多条数据,返回实体类集合List<Customer,通过BeanPropertyRowMapper自动映射实体属性
String querySQL = "select * from customer where id = ?";
List<Customer> customers = jdbcTemplate.query(querySQL, new BeanPropertyRowMapper<>(Customer.class), 10001);
new BeanPropertyRowMapper<>(Customer.class)可以自动映射实体属性,但是实体属性必须驼峰命名。可以使用BeanPropertyRowMapper.newInstance静态方法创建
String querySQL = "select * from customer where id = ?";
List<Customer> customers = jdbcTemplate.query(querySQL, BeanPropertyRowMapper.newInstance(Customer.class), 10001);
6、查询单条数据,返回实体类对象,通过BeanPropertyRowMapper自动映射实体属性
String querySQL = "select * from customer where id = ?";
List<Customer> customers = jdbcTemplate.queryForObject(querySQL, new BeanPropertyRowMapper

本文详细介绍了SpringBoot中JdbcTemplate的使用,包括查询单条/多条数据,插入、更新和删除记录,以及批处理操作。同时提到了如何利用BeanPropertyRowMapper进行对象映射,并展示了如何开启SQL日志。还介绍了NamedParameterJdbcTemplate,提供更直观的参数绑定方式。

1694

被折叠的 条评论
为什么被折叠?



