java - ORMLite 外国集合 : Must use ClosableIterator?

标签 java android dao ormlite foreign-collection

关于使用 ORMLite 的快速问题。我试图确保我的实现是正确的。文档的一部分讨论了 closableIterators 以及访问它如何加载 LazyForeignCollection 类,并且需要关闭(或读到最后)才能关闭数据库连接:

NOTE: Like with the Dao.iterator() method, the iterator returned by a lazy collection must be closed when you are done with it because there is a connection open to the database underneath. A close happens either if you go all of the way through the iterator or if you call close() on it. Only the ForeignCollection returns a closable iterator.

所以我的问题很简单:只能通过 closableIterator 访问集合吗?我是否可以像使用任何其他 Java 集合一样只使用 Collection/ForeignCollection 对象而不用担心数据库连接问题(例如:foreach 循环)?

最佳答案

我认为文档足以解释这一点。问题是完成后需要关闭连接,否则与 SQL 数据库的连接将保持打开状态。如果您使用 for (Account account : accountDao) 类型的模式,那么连接将在您一直通过时关闭 table 。如果您使用 break 或其他语句(return、goto、exception 等)在中间跳出循环,则 ORMLite 不会自动关闭连接。

如果您要跳出循环,那么文档中会指定要使用的正确模式。 http://ormlite.com/docs/iterator

CloseableIterator<Account> iterator = accountDao.closeableIterator();
try {
    while (iterator.hasNext()) {
        Account account = iterator.next();
        ...
    }
} finally {
    iterator.close();
}

您还可以使用“包装的可迭代对象”,它允许您在带有 for 循环的 finally 中执行关闭操作。

CloseableWrappedIterable<Account> wrappedIterable =
    accountDao.getWrappedIterable();
try {
    for (Account account : wrappedIterable) {
        ...
    }
} finally {
    wrappedIterable.close();
}

关于java - ORMLite 外国集合 : Must use ClosableIterator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7060867/

相关文章:

android - 在斜线和主要 Activity 之间分支 init

java - 如何对同时包含字符和整数的数组进行排序?

java - 导航在一个 Web View 中工作,但在另一个 Web View 中不起作用 - Android Studio

Java:寻找 hack 来处理 Linux 中的 Windows 文件路径

android - 您可以将数据库从 Android 设备传输到计算机上以用作 Android 虚拟设备中的数据库吗

java - 如何以编程方式设置壁纸?

java - 将God类重构为manager/dao/do分层架构

java - 使用 H2 数据库对 DAO 层进行单元测试

java - Room - 使用 MAX(numUsage) 获取对象

java - 将 Apache Velocity 与 StringBuilders/CharSequences 结合使用