JdbcTemplate自定义映射器
文章目录
(1)作用:结果集映射器BeanPropertyRowMapper的使用前提是数据库字段和对象属性
一致,
当不一致的时候,使用自定义映射器解决,将结果集转换成需要的对象
(2)自定义映射器代码如下
[Java]纯文本查看__复制代码
public class AccountRowMapper implements RowMapper<Account> {
/**
* 需要手动将结果集封装成对象
* @param rs 结果集(数据库里的字段)
* @param i 结果集所在的行: 下标从0开始
* @return 封装好的对象
* @throws SQLException
*/
@Override
public Object mapRow(ResultSet rs, int i) throws SQLException {
//1、新建实体类对象
Account account = new Account();
//2、设置属性值
account.setId(rs.getInt(`"id"`));
account.setUid(rs.getInt(`"uid"`));
account.setMoney(rs.getDouble(`"money"`));
//不同的字段(这里数据库没有,实体类有的字段)
account.setUserId(rs.getInt(`"id"`));
//3、返回对象
return account;
}
}
(3)测试映射器代码如下
[Java]纯文本查看__复制代码
@Test
public void testCustomMapper(){
//1、创建容器
ClassPathXmlApplicationContext ioc =
new ClassPathXmlApplicationContext(`"applicationContext.xml"`);
//2、获取工具类对象
JdbcTemplate jd = ioc.getBean(JdbcTemplate.`class`);
//3、操作数据库
String sql = "select * from account"`;`
List accountList = jd.query(sql, new AccountRowMapper());
accountList.forEach(System.out::println);
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论