RowMapper可以将数据中的每一行封装成用户定义的类,在数据库查询中,如果返回的类型是用户自定义的类型则需要包装。
public class ItemDAOImpl implements ItemDAO {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
//插入一条记录
public Item insert(Item item) {
String sql = "INSERT INTO items(user_id,name,phone,email) VALUES(?,?,?,?)";
Object[] params = new Object[]{item.getUserId(),item.getName(),item.getPhone(),item.getEmail()};
int[] types = new int[]{Types.INTEGER,Types.VARCHAR,Types.CHAR,Types.VARCHAR};
jdbcTemplate.update(sql,params,types);
return item;
}
public Item findById(int id) {
String sql = "SELECT * FROM items WHERE id = ?";
Object[] params = new Object[] {id};
int[] types = new int[] {Types.INTEGER};
List items = jdbcTemplate.query(sql,params,types,new ItemMapper());
if(items.isEmpty()){
return null;
}
return (Item)items.get(0);
}
public List<Item> findAllByUser(int user_id) {
String sql = "SELECT * FROM items WHERE user_id = ?";
Object[] params = new Object[]{user_id};
int[] types = new int[]{Types.INTEGER};
List items = jdbcTemplate.query(sql,params,types,new ItemMapper());
return items;
}
protected class ItemMapper implements 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.setPhone(rs.getString("phone"));
item.setEmail(rs.getString("email"));
return item;
}
调用:
public List findItemsBySQL(String sql) throws DataAccessException {
return (List)jdbcTemplate.query (sql,newRowMapperResultSetExtractor(new ItemMapper ()));
}
}
其用意就是通过该接口将查询到的每行记录信息都封装到一个entity类里边,方便使用。