JdbcTemplate RowMapper接口

时间:2020-12-27 17:52:59

JdbcTemplate调用queryXXX方法,其中通过BeanPropertyRowMapper实现类将获取的值封装到对象内。而BeanPropertyRowMapper是实现了RowMapper接口。

当pojo对象的属性与数据库中对应表的字段名不一致时,则需要自定RowMapper接口实现类,否则对象结果中的值为null或基本类型数据默认值。

    @Test
    public void queryAccount(){
        String sql="select id as ids,name as names,money as moneys from account where id=?";
        Account account = jdbcTemplate.queryForObject(sql, new RowMapper<Account>() { @Override public Account mapRow(ResultSet resultSet, int i) throws SQLException { Account account1=new Account(); account1.setId(resultSet.getInt("ids")); account1.setName(resultSet.getString("names")); account1.setMoney(resultSet.getFloat("moneys")); return account1; } }, 18);
        System.out.println(account);
    }