Spring JdbcDaoSupport 执行SQL
return int: getJdbcTemplate().queryForInt(sql) select count(*)...
return List:getJdbcTemplate().query(sql, rowMapper) select ... from ...
return null:getJdbcTemplate().update(sql) insert into ... values or delete from ...
return null:getJdbcTemplate().update(sql, objects, types) insert into ... values
return List:getJdbcTemplate().query(sql, new Object[] { assetId }, new int[] { Types.INTEGER }, rowMapper) select * from ... where id=
Object[] objects = new Object[]{user.getId(),user.getName(),user.getPassword()...};
int[] types = new int[]{Type.VARCHAR,Type.VARCHAR,Type.VARCHAR,...}
RowMapper对象
RowMapper的 mapRow() 方法是留给我们去组装实体类用的,返回是这种类的集合List
Public List<User> getUsers() {
String sql = "select * from User";
return getJdbcTemplate().query(sql,new ItemRowMapper());
}
protected class ItemRowMapper implements RowMapper { //这个类也可以定义在方法里如 RowMapper rowMapper = new RowMapper(){}
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Item item = new Item();
item.setId(rs.getInt("id"));
item.setUserId(rs.getInt("user_id"));
item.setName(rs.getString("name"));
item.setEmail(rs.getString("email"));
return item;
}
}
想象 getJdbcTemplate().query()方法 和 RowMapper类
public List query(String sql, RowMapper rowMapper){
int num = 0;
List<Object> list = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
conn = getConn();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
num = 0;
while(rs.next()){num++};
list = rowMapper.execute(rs, num);
}catch(Exception e){
}finall{
rs.close();
pstmt.close();
conn.close();
}
return list;
}
abstract Class RowMapper(){
List<Object> list = null;
public List execute(ResultSet rs, int rowNum){ //rowNum没用到
while(rs.next){
list.add(mapRow(rs, rowNum));
}
return list;
}
public Object mapRow(ResultSet rs, int RowNum);
}