Search code examples
javaspringjdbctemplate

Using Spring JdbcTemplate to extract two fields in a row


I am new to spring and my requiremnt is below: Using spring jdbctemplate extract two fields in a row.

I tried using queryFOrObject() api, which is working for one field, but I do not sure how to use it for two fields ?

public String getSalarayAndSalaryCode(int id) {
   JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

   //not working
    String sql = "SELECT salary,sal_code FROM table WHERE ID=?";

   //working
    String sql = "SELECT sal_code FROM table WHERE ID=?";

     String output= (String) jdbcTemplate.queryForObject(
        sql, new Object[] { id }, String.class);

   return output;
}

String sql = "SELECT salary,sal_code FROM table WHERE ID=?";

I want to get salary and sal_code in a single query.


Solution

  • You can do this by using queryForMap

    String sql = "SELECT salary,sal_code FROM table WHERE ID=?";
    Map<String, Object> result =  (Map<String, Object>) jdbcTemplate
                                  .queryForMap(sql, new Object[] {id});
    

    So Map contains

         Key           column
       column name     value
       column name     value