由ResultSet支持的Java Iterator [英] Java Iterator backed by a ResultSet

查看:145
本文介绍了由ResultSet支持的Java Iterator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现Iterator的类,ResultSet作为数据成员。本质上,类看起来像这样:

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有另一行,那么我可以创建一个有效的hasNext方法,因为ResultSet没有自己定义hasNext?我在考虑做 SELECT COUNT(*)FROM ... 查询以获取计数并管理该数字以查看是否有另一行但我想避免这种情况。

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.

推荐答案

这是一个坏主意。这种方法要求连接一直打开直到读取最后一行,并且在DAO层之外你永远不知道它何时会发生,并且你似乎也保持结果集开放并且风险资源泄漏和应用程序崩溃的情况下连接超时。你不想拥有它。

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做法是你获得连接 Statement 最短可能范围内的c>和 ResultSet 。通常的做法是你将多行映射到列表或者可能是 Map 并猜测是什么,它们 拥有 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.

不要像你最初想要的那样在DAO层之外传递昂贵的数据库资源。有关常规JDBC实践和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.

这篇关于由ResultSet支持的Java Iterator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆