REST api using java and spring boot

package com.propfinancing.CADData.web;

import com.propfinancing.util.db.MySQLUtil;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TXCollin {
  @Autowired
  private JdbcTemplate jdbcTemplate;

  @RequestMapping(method = RequestMethod.GET, value = "/TXCollin/getByIdAndYear")
  public  @ResponseBody Map<String,Object> getByIdAndYear(@RequestParam(value = "id") long id, @RequestParam(value = "year") int year) 
  throws Exception {
    StringBuffer sql = new StringBuffer("SELECT * from TXCollin_AD_Public WHERE");
    sql.append(" prop_id = "+MySQLUtil.NUMBER_FORMAT.format(id));
    sql.append(" AND curr_val_yr = "+MySQLUtil.NUMBER_FORMAT.format(year));
    sql.append(" ORDER BY pct_ownership DESC");
    sql.append(" LIMIT 1");
    HashMap<String,Object> valueMap = new HashMap<String,Object>();
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
      conn = jdbcTemplate.getDataSource().getConnection();
      stmt = conn.createStatement();
      rs = MySQLUtil.executeQuery(sql.toString(), stmt);
      if( rs.next() ) {
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        for( int i=1; i<=columnCount; i++ ) {
          String columnName = rsmd.getColumnName(i);
          Object value = rs.getObject(i);
          valueMap.put(columnName, value);
        }
      }
    } finally {
      try { rs.close(); } catch( Exception e ) { };
      try { stmt.close(); } catch( Exception e ) { };
      try { conn.close(); } catch( Exception e ) { };
    }
    if( !valueMap.isEmpty() )
      return valueMap;
    return null;
  }
}

Related Code Examples