I want to create a rest api which only perform some operations just like fetch data from mongodb and update it by name just like i fetch 5000 elements and i want to update id variable , can any one please help me on this ?
1 Answer
On the server side, I created a class which has the @RestContoller annotation. Next, you can declare methods with the @RequestMapping annotation which return a @ResponseBody.
Here is a sample class which is working in one of my applications:
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;
}
}
I can call it from a browser using the URL https://marketing.propfinancing.com/caddata/TXCollin/getByIdAndYear?id=54&year=2022
-
You can't actually load the URL since I have hidden it behind Spring Security, but it gives you the point. I also realize I am using raw SQL in this example and I could have used JPA. I chose not to do that for this application since I did not want to write a bunch of code for model classes and database interaction.– NeilCommented Mar 19, 2022 at 15:11