使用jdbcTemplate查询返回自定义对象集合代码示例

2025-05-29 0 62

1、在UserInfo.java中添加一个Map转换为UserInfo的方法

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18
public static UserInfo toObject(Map map) {

UserInfo userInfo = new UserInfo();

userInfo.setId((Integer) map.get(id));

userInfo.setUname((String) map.get(uname));

userInfo.setUnumber((Integer) map.get(unumber));

userInfo.setuRegisterTime((Date) map.get(uregister_time));

return userInfo;

}

public static List toObject(List> lists){

List userInfos = new ArrayList();

for (Map map : lists) {

UserInfo userInfo = UserInfo.toObject(map);

if (userInfo != null) {

userInfos.add(userInfo);

}

}

return userInfos;

}

dao层实现:

?

1

2

3

4

5
public List findAll() {

String sql = SELECT * FROM user_info;

List<Map<String,Object>> lists = jdbcTemplate.queryForList(sq);

return UserInfo.toObject(lists);

}

总结:这种方法能够实现,但是速度相比很慢。

2、使用jdbcTemplate.query(sql,RowMapper)方式实现:

dao层实现

?

1

2

3

4

5

6

7

8

9

10
jdbcTemplate.query(sql, new RowMapper<UserInfo>() {

@Override

public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {

UserInfo userInfo = new UserInfo();

userInfo.setUname(rs.getString("uname"));

userInfo.setUnumber(rs.getInt("unumber"));

userInfo.setuRegisterTime(rs.getDate("uregister_time"));

return userInfo;

}

});

总结:在其他查询方法中无法重用。

3、 使用RowMapper实现接口方式,覆盖mapRow方法:

?

1

2

3

4

5

6

7

8

9

10

11
public class UserInfo implements RowMapper, Serializable{

@Override

public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {

UserInfo userInfo = new UserInfo();

userInfo.setId(rs.getInt(id));

userInfo.setUname(rs.getString(uname));

userInfo.setUnumber(rs.getInt(unumber));

userInfo.setuRegisterTime(rs.getDate(uregister_time));

return userInfo;

}

}

dao层实现:

?

1

2

3

4

5

6

7

8

9

10

11
public UserInfo getById(Integer id) {

String sql = SELECT * FROM user_info WHERE id = ?;

UserInfo userInfo = jdbcTemplate.queryForObject(sql, new UserInfo(), new Object[] { id });

return userInfo;

}

public List findAll() {

String sql = SELECT * FROM user_info;

List userInfos = jdbcTemplate.query(sql, new UserInfo());

return userInfos;

}

4、dao层使用

?

1
jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<UserInfo>(Qsfymxb.class));

Spring 提供了一个便利的RowMapper实现—–BeanPropertyRowMapper

它可自动将一行数据映射到指定类的实例中 它首先将这个类实例化,然后通过名称匹配的方式,映射到属性中去。

例如:属性名称(vehicleNo)匹配到同名列或带下划线的同名列(VEHICLE_NO)。如果某个属性不匹配则返回属性值为Null

总结

以上就是本文关于使用jdbcTemplate查询返回自定义对象集合代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

原文链接:http://blog.csdn.net/u011332918/article/details/45560117

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 使用jdbcTemplate查询返回自定义对象集合代码示例 https://www.kuaiidc.com/112432.html

相关文章

发表评论
暂无评论