Search code examples
springspring-bootspring-data-jpaspring-jdbcjdbctemplate

Convert to simplejdbccall resultset to java objects


I am calling DB2 procedure which takes a input parameter and returns a resultset. How can i map the O/P to my pojo class. I have to map the result to nexted pojo classes.

    simpleJdbcCall = new SimpleJdbcCall(jdbctemplate)
                    .withSchemaName("myschema")
                    .withProcedureName("DB2-PROC")
                    .declareParameters(
                            new SqlParameter("1", Types.VARCHAR)
                        );
                        
    Map<String, Object> map =   simpleJdbcCall.execute("2020-01-01");
    
    for (Map.Entry<String, Object> entry : map.entrySet()) {
  System.out.println("Entry value  is " + entry.getValue() );
    }
        
        //my o/p
        Entry value  is [{Col_1=abc, col_2=abc,col_2=xyz, col_2=abc},....];    

Solution

  • you can use returningResultSet(parameterName, rowMapper) method to map values to object.

    Here some reference code:

    SimpleJdbcCall procedureActor = new SimpleJdbcCall(dataSource)
                .withSchemaName("myschema")
                .withProcedureName("DB2-PROC")
                .declareParameters(
                        new SqlParameter("1", Types.VARCHAR))
                .returningResultSet("mapObjRefrence", new RowMapper<Contact>() {
         
                    @Override
                    public Contact mapRow(ResultSet rs, int rowNum) throws SQLException {
                        YourPojo pojo = new YourPojo();
                         
                        pojo.setId(rs.getInt("col_1"));
                        pojo.setName(rs.getString("col_2"));
                        pojo.setEmail(rs.getString("col_2"));
                        pojo.setAddress(rs.getString("col_3"));
                        pojo.setTelephone(rs.getString("col_4"));
                         
                        return contact;
                    }
                });
         
        Map<String, Object> out = procedureActor.execute("2020-01-01");
         
        List<YourPojo> listPojos = (List<YourPojo>) out.get("mapObjRefrence");
    

    Also you can check for multi table results: How to get multi table results using SimpleJDBCCall in spring?