Java – How do I map multiple rows in a single object?

How do I map multiple rows in a single object?… here is a solution to the problem.

How do I map multiple rows in a single object?

I want to map multiple rows into one object. Here is my result set

Id        Name       Marks
1         A          34
2         b          35

My class is like this:

public class student {
    int id;
    String name;
    List <Integer> marks;
}

I tried using RowMapper, but that was for a 1:1 black and white relationship between rows and objects. Please suggest me the right way to achieve this?

Thanks in advance.

Solution

Nico Van Belle’s approach using ResultSetExtractor is a way to go, Unless you will return a Collection <Student> not a single Student purpose.

Implement When ResultSetExtractor<T>, Spring provides you with the complete ResultSet (all rows returned from the DB). Implementing the logic of how to extract data/objects is your responsibility (and freedom) and you want to return as a (complete) result. The result is a single object, such as a setting or a list (student object).

Here’s a rough example:

new ResultSetExtractor<Collection<Student>>() {
    @Override
    public Collection<Student> extractData(ResultSet rs) throws SQLException, DataAccessException {
        Map<Integer, Student> studentMap = new HashMap<>();

while(rs.next()){
            Integer id = rs.getInt(0);
            Student student = studentMap.get(id);

if (student == null) {
                String name = rs.getString(1);
                student = new Student(id, name);  additional constructor for Student class
                studentMap.put(id, student);
            }

student.addMark(rs.getInt(3));
        }

return studentMap.values();
    }
});

Related Problems and Solutions