Skip to content
Advertisement

Dynamic update query for multiple columns using spring MVC

I am having a JSON data as shown below:

{
    "table" : "customer",
    "uniqueColumn" : "customer",
    "uniqueColVal" : "cust_786",
    "columns" : 
    [{
        "column_1" : "column_1 Val",
        "column_2" : "column_2 Val",
        "column_..." : "column_... Val",
        "column_..." : "column_... Val",
        "column_..." : "column_... Val",
        "column_n" : "column_n Val"
    }]
}

I need a query to be executed and should be in the below form

UPDATE customer SET column_1 = 'column_1 Val', column_2 = 'column_2 Val', column_... = 'column_... Val', column_n = 'column_n Val' WHERE customer = 'cust_786';

I am using Spring MVC for processing this and the code I wrote is as follows. It is not complete.

@Override
public Map<String, Object> updateTabColumnValues(Map<String, Object> data)
{
    Map<String, Object> response = new HashMap();
    try 
    {
        String table= data.get("table").toString();
        String uniqueid = data.get("uniqueid").toString();
        
        if (table!=null && uniqueid !=null)
        {
            String column = null, columnVal = null, updateColumn = null, updateColumnVal = null;
            JSONObject jsonObj = new JSONObject(data);
            JSONArray columnsToUpdate = jsonObj.getJSONArray("columns");
            for (int i = 0; i < columnsToUpdate.length(); i++)
            {
                if (i == columnsToUpdate.length() - 1)
                {
                    JSONObject json_Obj = columnsToUpdate.getJSONObject(i);
                    column = json_Obj.keys().next().toString();
                    columnVal = json_Obj.getString(column).toString();
                    updateColumn = updateColumn + column.toString();
                    updateColumnVal = updateColumnVal + " = " + columnVal.toString() + "'";
                }
            }
            System.out.println("UPDATE " + table+ " SET " + updateColumn +" = " + updateColumnVal + " WHERE " + data.get("uniqueColumn").toString() +" = '" + data.get("uniqueColVal").toString() +"';");
        }
        else
        {
            response.put("status", false);
            LOGGER.info("Failed to get table>>> " + table+ " OR uniqueid >>> " + uniqueid);
        }
    } 
    catch (Exception e) 
    {
        response.put("status", false);
        LOGGER.error("Error @editLayerAttributeByUniqueID ", e);
        System.err.println("Error @editLayerAttributeByUniqueID " + e);         
    }
    return response;
}

It would be very much helpful if someone could help me out here. Thanks in advance.

Advertisement

Answer

I could find a satisfying answer at the end. Please follow the below instructions.

You need to import some packages and I am mentioning the Maven repository for the same below. Add the dependency in your pom.xml

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>
<!-- For PostgreSQL Database connectivity -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.3.0.RELEASE</version>
</dependency>

Now Import the packages in your Impl file as follows:

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.jdbc.core.JdbcTemplate;

The logic is explained in the below code

public JdbcTemplate getJdbcTemplate() 
{
    return jdbcTemplate;
}

@Override
//Defines a Map named as updateTabColumnValues to get data from client
public Map<String, Object> updateTabColumnValues(Map<String, Object> data)
{
    //Defines a Map named as response to send data to client
    Map<String, Object> response = new HashMap();
    try 
    {
        String table = data.get("table").toString();
        String uniqueColumn = data.get("uniqueColumn").toString();
        String uniqueValue = data.get("uniqueValue").toString();
        if ((uniqueColumn != null && uniqueValue != null) && table != null)
        {
            String column;
            String columnVal;
            String keyValuePair = "";
            String query = null;
            JSONObject jsonObj = new JSONObject(data);
            //Gets values in the key columns to columnsToUpdate 
            JSONArray columnsToUpdate = jsonObj.getJSONArray("columns");
            //Loops each elements with in the array
            if (columnsToUpdate.length() > 0)
            {
                for (int i = 0; i < columnsToUpdate.length(); i++)
                {
                    if (i == columnsToUpdate.length() - 1)
                    {
                        //Create Key Value pair without adding comma at the end
                        JSONObject json_Obj = columnsToUpdate.getJSONObject(i);
                        column = json_Obj.keys().next();
                        columnVal = json_Obj.getString(column);
                        keyValuePair = keyValuePair + column + " = '" + columnVal + "'";
                    }
                    else
                    {
                        //Create Key Value pair with comma at the end
                        JSONObject json_Obj = columnsToUpdate.getJSONObject(i);
                        column = json_Obj.keys().next();
                        columnVal = json_Obj.getString(column);
                        keyValuePair = keyValuePair + column + " = '" + columnVal + "' , ";
                    }
                }
                    
                int queryValidator = -1;
                query = "UPDATE " + table +" SET "+ keyValuePair + " WHERE " + uniqueColumn + " = '" + uniqueValue +"';";
                LOGGER.info("Query is >>> " + query);
                //Uses getJdbcTemplate() to run query
                queryValidator = getJdbcTemplate().update(query);
                    
                //Validating the query execution status with database
                if (queryValidator >= 0) 
                {
                    response.put(stateOfstatus,true);
                } 
                else 
                {
                    response.put(stateOfstatus,false);
                }
            }
            else
            {
                response.put(stateOfstatus, false);
            }
        }
        else
        {
            response.put(stateOfstatus, false);
            LOGGER.info("Failed to get table >>> " + table + " OR uniqueColumn >>> " + uniqueColumn + " OR uniqueValue >>>" + uniqueValue);
        }
    } 
    catch (Exception e) 
    {
        response.put(stateOfstatus, false);
        LOGGER.error("Error in updateTabColumnValues ", e);
        response.put("message", e);
    }
    return response;
}

This was an RnD related task taken under a special usecase. The above logic perfectly and effectivelty delivers the output.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement