ORMLite ForeignCollection: Must use ClosableIterator?

我只是一个虾纸丫 提交于 2019-12-10 10:26:34

问题


quick question about using ORMLite. I am trying to make sure that my implementation is correct. There's a part of the documentation that talks about closableIterators and how accessing this loads the LazyForeignCollection class and it needs to be closed (or read to the end) for the database connection to be closed:

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.

So my question is simply: can the collection be accessed only through the closableIterator? Am I able to just use a Collection / ForeignCollection object as I would any other Java collection and not worry about the database connection stuff (say for example: foreach loop)?


回答1:


I thought the documentation would be enough to explain this. The issue is that the connection needs to be closed when you are done otherwise the connection to the SQL database will be left open. If you use a for (Account account : accountDao) type of pattern then the connection will only be closed if you go all of the way through the table. If you use a break or other statement (return, goto, exception, etc.) to break out of the loop in the middle then the connection will not be closed automatically by ORMLite.

If you are going to break out of your loop then the proper pattern to use is specified in the docs. http://ormlite.com/docs/iterator

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

You can also use the "wrapped iterable" which allows you to do the close in the finally with for loops.

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


来源:https://stackoverflow.com/questions/7060867/ormlite-foreigncollection-must-use-closableiterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!