JdbcTemplate自定义映射器

(1)作用:结果集映射器BeanPropertyRowMapper的使用前提是数据库字段和对象属性
一致,
当不一致的时候,使用自定义映射器解决,将结果集转换成需要的对象
(2)自定义映射器代码如下
[Java]

纯文本查看

复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

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]

纯文本查看

复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

@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);

}

发布了964 篇原创文章 · 获赞 11 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/xiaoyaGrace/article/details/105400408