2014-09-24 60 views
0

多個表的數據必須映射到單個bean。將多個表數據映射到Spring中的單個bean jdbc

在這種情況下,id,name將從其他表格中的一個表中檢索出optionList。所以來自n個表的數據應該與單個bean相匹配。什麼是使用RowMapper or ResultSetExtractor or any alternative的最佳方法。 BeanPropertyRowMapper和RowMapper之間的性能差異是什麼。

我的模型類是這樣的:

class Preference{ 
    int id; 
    int name; 
    List<Option> optionList; //will be retrieved from other table. 
    String contactName; 
    String ContactTitle; 
} 

回答

0

你可以使用Spring行映射器來完成這項工作。 http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#jdbc-JdbcTemplate-examples-query

差不多有的像

public class MyRowMapper implements RowMapper<MyCustomEntity> { 

    @Override 
    public MyCustomEntity mapRow(ResultSet rs, int rowNum) throws SQLException { 
     MyCustomEntity custom = new MyCustomEntity(); 

     custom.setId(rs.getLong("id")); 
     custom.setName(rs.getString("name")); 
     custom.setMoreData(rs.getString("more_data")); 

     return custom; 
    } 

} 

在你的DAO的傢伙,你可以這樣做

@Repository 
public class DaoGuy { 

    @Inject 
    private JdbcTemplate jdbcTemplate; 

    public List<MyCustomEntity> getMyCustomEntityData(String whateverYouWantToUseToFilter) { 
     String sqlQuery = "select a.id, b.name, c.more_data from my tablea a, tableb b, tablec c"; 
     return jdbcTemplate.query(sqlQuery, new MyRowMapper()); 

    } 

}