【发布时间】:2011-09-22 14:27:43
【问题描述】:
我有一个实现 RowMapper 接口的行映射器类。我需要在其中实现 mapRow 方法。它的参数是 ResulSet 和 index。我想在另一个 bean 中使用这个 ResultSet 对象。我怎么去那里?
【问题讨论】:
标签: spring
我有一个实现 RowMapper 接口的行映射器类。我需要在其中实现 mapRow 方法。它的参数是 ResulSet 和 index。我想在另一个 bean 中使用这个 ResultSet 对象。我怎么去那里?
【问题讨论】:
标签: spring
将此对象设置为实例变量。但我绝不会为 ResultSet 推荐它。结果集在 spring 关闭后将无用(因为 spring 正在管理它)。
最好从 ResultSet 中提取数据,将数据作为一些模型 bean 存储在实例变量中(但请记住,默认情况下,bean 是单例的,并且对于每次执行,将数据存储为实例变量也没有多大意义)。
编辑--可以再完善一下,我在这里举个例子
// this is singleton by default, if you want to store data in this bean
// mark it as bean either by annotation or thorugh xml
// so that it can be accessed through spring context
public class MyBeanRowMapper implements RowMapper
{
// you can store something here,
// but with each execution of mapRow, it will be updated
// not recommended to store execution result here
// or inject other bean here // SomeOtherBean someOtherbean;
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
MyBean myBean = new MyBean();
myBean.setId(rs.getInt("BEAN_ID"));
myBean.setName(rs.getString("NAME"));
// set this bean into gloablly accessible object here
// or to the bean in which you want to access the result
// something like -->// someOtherBean.setMyBean(myBean)
// again be careful if someOtherBean is singleton by default
return myBean;
}
}
【讨论】: