bharghavi vajrala
bharghavi vajrala

Reputation: 61

Mapping of multiple table data to single bean in Spring jdbc

Data of multiple tables has to be mapped to single bean.

In this case id,name will be retrieved from one table, optionList from other table. So data from n number of tables should be matched to single bean. What would be the best approach using RowMapper or ResultSetExtractor or any alternative. What would be the performance difference between BeanPropertyRowMapper and RowMapper.

My model class is like:

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

Upvotes: 1

Views: 2562

Answers (1)

Desorder
Desorder

Reputation: 1539

You can use Spring Row Mapper to do the job. http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#jdbc-JdbcTemplate-examples-query

Pretty much some like

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;
    }

}

In your DAO guy, you can do something like

@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());

    }

}

Upvotes: 1

Related Questions