問(wèn)題描述
我有一個(gè)使用 ResultSet 作為數(shù)據(jù)成員來(lái)實(shí)現(xiàn) Iterator 的類.基本上這個(gè)類看起來(lái)像這樣:
I've got a class that implements Iterator with a ResultSet as a data member. Essentially the class looks like this:
public class A implements Iterator{
private ResultSet entities;
...
public Object next(){
entities.next();
return new Entity(entities.getString...etc....)
}
public boolean hasNext(){
//what to do?
}
...
}
我如何檢查 ResultSet 是否有另一行,以便創(chuàng)建有效的 hasNext 方法,因?yàn)?ResultSet 本身沒(méi)有定義 hasNext?我正在考慮執(zhí)行 SELECT COUNT(*) FROM...
查詢以獲取計(jì)數(shù)并管理該數(shù)字以查看是否還有另一行,但我想避免這種情況.
How can I check if the ResultSet has another row so I can create a valid hasNext method since ResultSet has no hasNext defined itself? I was thinking doing SELECT COUNT(*) FROM...
query to get the count and managing that number to see if there's another row but I'd like to avoid this.
推薦答案
這是個(gè)壞主意.這種方法要求在讀取最后一行之前一直打開連接,并且在 DAO 層之外你永遠(yuǎn)不知道它什么時(shí)候會(huì)發(fā)生,而且你似乎也讓結(jié)果集保持打開狀態(tài),并在這種情況下冒著資源泄漏和應(yīng)用程序崩潰的風(fēng)險(xiǎn)連接超時(shí).你不想擁有那個(gè).
This is a bad idea. This approach requires that the connection is open the whole time until the last row is read, and outside the DAO layer you never know when it will happen, and you also seem to leave the resultset open and risk resource leaks and application crashes in the case the connection times out. You don't want to have that.
正常的 JDBC 實(shí)踐是在 最短 可能的范圍內(nèi)獲取 Connection
、Statement
和 ResultSet
.通常的做法是將多行映射到一個(gè) List
或者可能是一個(gè) Map
并猜猜是什么,他們 確實(shí) 有一個(gè) Iterator
.
The normal JDBC practice is that you acquire Connection
, Statement
and ResultSet
in the shortest possible scope. The normal practice is also that you map multiple rows into a List
or maybe a Map
and guess what, they do have an Iterator
.
public List<Data> list() throws SQLException {
List<Data> list = new ArrayList<Data>();
try (
Connection connection = database.getConnection();
Statement statement = connection.createStatement("SELECT id, name, value FROM data");
ResultSet resultSet = statement.executeQuery();
) {
while (resultSet.next()) {
list.add(map(resultSet));
}
}
return list;
}
private Data map(ResultSet resultSet) throws SQLException {
Data data = new Data();
data.setId(resultSet.getLong("id"));
data.setName(resultSet.getString("name"));
data.setValue(resultSet.getInteger("value"));
return data;
}
如下使用:
List<Data> list = dataDAO.list();
int count = list.size(); // Easy as that.
Iterator<Data> iterator = list.iterator(); // There is your Iterator.
不要像最初想要的那樣將昂貴的數(shù)據(jù)庫(kù)資源傳遞到 DAO 層之外.有關(guān)常規(guī) JDBC 實(shí)踐和 DAO 模式的更多基本示例,您可以找到 這篇文章很有用.
Do not pass expensive DB resources outside the DAO layer like you initially wanted to do. For more basic examples of normal JDBC practices and the DAO pattern you may find this article useful.
這篇關(guān)于由 ResultSet 支持的 Java 迭代器的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!