一: JdbcTemplate查询-RowMapper返回自定义对象
目标
能够掌握JdbcTemplate中RowMapper返回自定义对象
讲解
org.springframework.jdbc.core.JdbcTemplate类方便执行SQL语句
API介绍
public <T> List<T> query(String sql, RowMapper<T> rowMapper)
执行查询语句,返回一个List集合,List中存放的是RowMapper指定类型的数据。
使用步骤
定义Product类
创建JdbcTemplate对象
编写查询的SQL语句
使用JdbcTemplate对象的query方法,并传入RowMapper匿名内部类
在匿名内部类中将结果集中的一行记录转成一个Product对象
案例代码
// query使用rowMap做映射返回一个对象
public static void test06() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
// 查询数据的SQL语句
String sql = "SELECT * FROM product;";
List<Product> query = jdbcTemplate.query(sql, new RowMapper<Product>() {
@Override
public Product mapRow(ResultSet arg0, int arg1) throws SQLException {
Product p = new Product();
p.setPid(arg0.getInt("pid"));
p.setPname(arg0.getString("pname"));
p.setPrice(arg0.getDouble("price"));
return p;
}
});
for (Product product : query) {
System.out.println(product);
}
}
案例效果

小结
RowMapper的使用?
List<T> query(String sql, RowMapper<T> rowMapper, Object... args)
传入RowMapper匿名内部类,实现mapRow方法,在mapRow方法中获取结果集中的一条记录,并创建对象,将这条记录中的数据存储到对象中.
二: JdbcTemplate查询-BeanPropertyRowMapper返回自定义对象
目标
能够掌握JdbcTemplate中BeanPropertyRowMapper返回自定义对象
讲解
org.springframework.jdbc.core.JdbcTemplate类方便执行SQL语句
API介绍
public <T> List<T> query(String sql, RowMapper<T> rowMapper)
执行查询语句,返回一个List集合,List中存放的是RowMapper指定类型的数据。
public class BeanPropertyRowMapper<T> implements RowMapper<T>
BeanPropertyRowMapper类实现了RowMapper接口
使用步骤
定义Product类
创建JdbcTemplate对象
编写查询的SQL语句
使用JdbcTemplate对象的query方法,并传入BeanPropertyRowMapper对象
案例代码
// query使用BeanPropertyRowMapper做映射返回对象
public static void test07() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
// 查询数据的SQL语句
String sql = "SELECT * FROM product;";
List<Product> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Product.class));
for (Product product : list) {
System.out.println(product);
}
}
案例效果

小结
BeanPropertyRowMapper的使用?
template.query(sql, new BeanPropertyRowMapper<>(Product.class), 5);JdbcTemplate的query方法用于执行SQL语句,简化JDBC的代码。同时还可以在SQL语句中使用?占位,在query方法的Object... args可变参数中传入对应的参数。
文章转载自老李的Java学习日记,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




