gpt4 book ai didi

Java - 使用 iBatis 从数据库中检索大量数据

转载 作者:行者123 更新时间:2023-12-04 07:04:24 24 4
gpt4 key购买 nike

我需要从 DB2 表中提取数据,对每个返回的行运行一些处理并输出到平面文件。我正在使用 iBatis,但发现使用 查询列表 我开始出现内存错误,我将看到 100k+ 行数据增加。

我看过使用 queryWithRowHandler 而是 iBatis 行处理程序 接口(interface)不会从其 中抛出异常处理行 函数,所以如果它出现错误,我无法正确报告它并停止迭代其余数据。看起来我可以抛出一个 RuntimeException ,但这并没有让我觉得这是一种简洁的做事方式。

我希望能够在抛出一个有意义的异常时停止处理,指示错误是否发生在数据操作、文件访问或其他方面。

有没有人有过这种方法的经验或有使用 iBatis 的替代解决方案。我知道我可以在没有 iBatis 的情况下仅使用 JDBC 来执行此操作,但是由于 iBatis 用于我的应用程序中的所有其他数据库访问,因此我希望尽可能利用此架构。

最佳答案

1)创建您自己的 RowHandler 接口(interface),并在签名中检查异常:

public interface MySpecialRowHandler {
public void handleRow(Object row)
throws DataException, FileException, WhateverException;
}

2) 从 SqlMapDaoTemplate 继承(甚至更好, delegate )以添加一个新方法,该方法将管理您自己的处理程序,签名中具有相同的异常:
public class MySpecialTemplate extends SqlMapDaoTemplate {
...
public void queryWithRowHandler(String id,
final MySpecialRowHandler myRowHandler
) throws DataException, FileException, WhateverException {
// "holder" will hold the exception thrown by your special rowHandler
// both "holder" and "myRowHandler" need to be declared as "final"
final Set<Exception> holder = new HashSet<Exception>();
this.queryWithRowHandler(id,new RowHandler() {
public void handleRow(Object row) {
try {
// your own row handler is executed in IBatis row handler
myRowHandler.handleRow(row);
} catch (Exception e) {
holder.add(e);
}
}
});
// if an exception was thrown, rethrow it.
if (!holder.isEmpty()) {
Exception e = holder.iterator().next();
if (e instanceof DataException) throw (DataException)e;
if (e instanceof FileException) throw (FileException)e;
if (e instanceof WhateverException) throw (WhateverException)e;
// You'll need this, in case none of the above works
throw (RuntimeException)e;
}
}
}

3)您的业务代码将如下所示:
// create your rowHandler
public class Db2RowHandler implements MySpecialRowHandler {
void handleRow(Object row) throws DataException, FileException, WhateverException {
// what you would have done in ibatis RowHandler, with your own exceptions
}
}
// use it.
MySpecialTemplate template = new MySpecialTemplate(daoManager);
try {
template.queryWithRowHandler("selectAllDb2", new Db2RowHandler());
} catch (DataException e) {
// ...
} catch (FileException e) {
...

关于Java - 使用 iBatis 从数据库中检索大量数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1344362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com