【问题标题】:Mapping of multiple table data to single bean in Spring jdbcSpring jdbc中多个表数据到单个bean的映射
【发布时间】:2014-09-24 02:26:32
【问题描述】:

多个表的数据必须映射到单个 bean。

在这种情况下,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; 
}

【问题讨论】:

    标签: java spring jsp jdbc db2


    【解决方案1】:

    您可以使用 Spring Row Mapper 来完成这项工作。 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());
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多