2017-02-09 15 views
0

我想將多個行映射到一個對象。這是我的resultSet如何在單個對象中映射多行?

Id  Name  Marks 
1  A   34 
2  b   35 

我的班是一樣的東西

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

我使用RowMapper的嘗試,但也就是1:1的關係的B/W行和對象。請建議我採用正確的方法來實現這一目標?

在此先感謝

+0

在這個例子中每一行都有不同的'Id'和'Name',但你的'student'類(這應該是計劃** S ** tudent)有一個'id'和'name'屬性。多行如何適合一個'學生'? –

+0

這只是一個例子,實際上可以有相同的ID和名稱。 @AndrewS –

回答

1

Nico Van Belle's approach使用ResultSetExtractor是很長的路要走,除非你將返回Collection<Student>而不是單個Student對象。

當實現ResultSetExtractor<T>時,Spring爲您提供了完整的ResultSet(從DB返回的所有行)。這是你的責任(和自由)來實現邏輯如何提取數據/對象,你想返回一個(完整的)結果。結果是單個對象,例如設置或列出(學生對象的)。

這裏是一個粗略的例子:

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(); 
    } 
}); 
0

在不是在一個對象每1分的結果,你可以使用ResultSetExtractor類的情況。你的最終解決方案應該類似於這個粗略的例子。

new ResultSetExtractor<Student>() { 
    @Override 
    public Student extractData(ResultSet rs) throws SQLException, DataAccessException { 
     Student student = new Student(); 
     while(rs.next()){ 
      // internal logic where you set id, name and add marks to the list 
      student.addMark(rs.getInt(3)); 
     } 
     return student; 
    } 
}); 
+0

ID名稱標誌 1 A 34 2 B 35 –

+0

我希望我的ResultSetExtractor類是像 新ResultSetExtractor類(){ @覆蓋 公開名單 ExtractData由(RS ResultSet的)拋出的SQLException,DataAccessException的{ 名單學生= new ArrayList ; while(rs.next()){ //內部邏輯,您在其中設置標識,名稱並將標記添加到列表中 \t \t Student s = new Student(); s.setId(rs.getInteger(「id」)); s.setName(rs.getString(「name」)); \t s.setmarks(new ArrayList ().add(rs.getmarks(「marks」))); \t } return student; } }); –

+0

如果我用你的方法,每次必須使用studentId在列表中進行搜索,並使用當前rs中獲得的新標記更新標記列表。這對我來說不太合適。有沒有其他的我可以關注?@ Nico Van Belle –

相關問題