RowMapper 将多个结果放入列表属性

RowMapper put multiple results into list attribute

我想在 Spring 中 运行 一个 JDBC 查询(在 SQL 服务器上),这将(松散地)得到以下 table:

+-----------------+
| ID Text Country |
+-----------------+
| 1  Test US      |
| 1  Test UK      |
+-----------------+

我想像这样把它放在 Java class 中:

class TestClass {
    private int id;
    private String text;
    private List<String> country;
}

所以,上面应该只给我一个对象。 I/how 我可以用 RowMapper 做这个吗?如果我有

public TestClass mapRow(ResultSet rs, int rowNum) throws SQLException {
    TestClass test = new TestClass();
    test.setId(rs.getInt("ID"));
    test.setText(rs.getString("Text"));
    return test;
}

我无法真正聚合多行,因为 RowMapper(顾名思义)作用于行。

我以前用 Hibernate 做过这个,它可以工作,但是非常慢,所以我想尽快在 SQL 服务器上生成所有需要的结果。因为我只需要创建一个 JSON 对象的结果,我想如果我在 String 基础上工作就可以了。

谢谢!

您必须使用 ResultSetExtractor 而不是 RowMapper。

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

public class DBReader implements ResultSetExtractor {

@Override
public Object extractData(ResultSet rs) throws SQLException,
        DataAccessException {

    Map<String, TestClass> items = new HashMap<String, TestClass>();

    while(rs.next()) {

        TestClass test = items.get(rs.getString("ID"));

        if (test == null) {

            test = new TestClass();
            test.setId(rs.getInt("ID"));
            test.setText(rs.getString("Text"));

        } 

        test.getCountry().add(rs.getString("Country"));
    }

    return items;
}

}

在您的 TestClass 中,更改您的国家/地区列表持有者,如下所示

    private List<String> country = new ArrayList<String>();