Spring中RowMapper接口的作用:
用来把数据库中的列字段和java bean中属性对应上,这样就可以赋值了
sping中的RowMapper可以将数据中的每一行数据封装成用户定义的类。
我们在数据库查询中,如果返回的类型是用户自定义的类型(其实我们在数据库查询中大部分返回的都是自定义的类)则需要包装,如果是Java自定义的类型,如:String则不需要。
如果sping与hibernate 相结合了,基本上是用不到,大多数都是在spring单独使用时用到,常见的情况就是与JdbcTemplate一起使用。
可以通过建立内部类实现RowMapper接口,RowMapper中有一个mapRow方法,所以实现RowMapper接口一定要实现mapRow方法,而对自定义类的包装就在mapRow方法中实现。
用法
调用RowMapper接口,必须重写 mapRow方法。
public class StudentMarksMapper implements RowMapper<StudentMarks> {
public StudentMarks mapRow(ResultSet rs, int rowNum) throws SQLException{
StudentMarks studentMarks = new StudentMarks();
studentMarks.setId(rs.getInt("id"));
}
}
将数据库中id与StudentMark类中的id对应起来。