我找到了几个如何将自定义 ResultHandler 连接到 MyBatis 查询的示例:
例如https://code.google.com/p/mybatis/wiki/ResultHandlerExample
不幸的是,示例中给出的 ResultHandler 永远不会被调用。 (正如最后一条评论已经指出的那样)
所以我寻找解决方案并发现了这个:MyBatis - ResultHandler is not invoked
但这不太适合我的问题,因为我使用的是 xml 风格的 MyBatis,而不是 API 风格的方式。所以就我而言,我没有
SqlSession session = MyBatisConnectionFactory.getSqlSessionFactory().openSession(true);
有没有办法在 xml 文件中连接我的自定义处理程序,例如
<resultMap />
oder <select />
节点?
您可以在映射器中使用 ResultHandler 定义方法:
public interface YourMapper {
void getObjects(@Param("param1") Object param1, ResultHandler handler);
}
然后就可以使用它了:
List<Object> getObjects(object param1) {
YourResultHandler resultHandler = new YourResultHandler();
yourMapper.getObjects(param1, resultHandler);
return resultHandler.getResults();
}
你可以像这样定义映射器:
public interface YourMapper {
void list(@Param("param1") Object param1, ResultHandler handler);
}
在 xml 中:
<select id="list" parameterType="map" resultType="map">
SELECT *
FROM
<include refid="tableName"/>
WHERE param1=#{param1}
</select>
这是你的
resultHandler
:
public class CustomResultHandler implements ResultHandler<List<CustomResult>> {
@Getter
private List<CustomResult> customResults;
@Override
public void handleResult(ResultContext rc) {
Map<String,Object> results = (Map<String,Object>)rc.getResultObject();
///this func is called once on each row found, let store result to `customResults`
}
}
来电者将如下所示:
public List<CustomResult> list(String param1) {
CustomResultHandler resultHandler = new CustomResultHandler();
mapper.list(param1,resultHandler);
return resultHandler.getCustomResults();
}