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

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章