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层实现:
总结:这种方法能够实现,但是速度相比很慢。
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