【问题标题】:How to turn a ResultSet into a DTO ArrayList如何将 ResultSet 变成 DTO ArrayList
【发布时间】:2016-08-09 23:01:23
【问题描述】:

我有一个来自数据库的 ResultSet,每行包含 6 列。

对我来说,每一行都是一个对象,每一列都是该对象的一个​​参数。

问题是,我正在尝试使用以下代码:

while(rs.next() && i<25){
        aux.setIdVinilo(rs.getInt("id_vinilo"));
        aux.setTitulo(rs.getString("titulo"));
        aux.setAutor(rs.getString("autor"));
        aux.setGenero(rs.getString("genero"));
        aux.setFecha(rs.getInt("fecha"));
        aux.setDiscografica(rs.getString("discografica"));
        aux.setImagen(rs.getString("imagen"));

        historial.add(aux);
        i++;
    } 

rs 是 ResultSet,historial 是 ArrayList,aux 是我的 DTO,由显示的字段组成。

问题在于它最终会用相同的信息填充 ArrayList 25 次。所以我猜 rs.next() 在每次迭代后不会向前移动一行。我如何做到这一点?

【问题讨论】:

    标签: java database arraylist resultset


    【解决方案1】:

    问题是你一次又一次地设置同一个对象 您需要在循环内创建一个新对象

    while(rs.next() && i<25){                    
            DTO aux=new DTO();// create aux object here
    
            aux.setIdVinilo(rs.getInt("id_vinilo"));
            aux.setTitulo(rs.getString("titulo"));
            aux.setAutor(rs.getString("autor"));
            aux.setGenero(rs.getString("genero"));
            aux.setFecha(rs.getInt("fecha"));
            aux.setDiscografica(rs.getString("discografica"));
            aux.setImagen(rs.getString("imagen"));
    
            historial.add(aux);
            i++;
    } 
    

    【讨论】:

    • 是的!就是这样,非常感谢!我会尽快接受答案^^
    • @rev_dihazum 感谢编辑
    【解决方案2】:

    在while循环中创建DTO对象

    【讨论】:

      猜你喜欢
      • 2010-10-13
      • 2014-11-25
      • 1970-01-01
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 2012-02-23
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多