In my spring-boot application, I'm receiving json data from an API, and I need to persist this data, without having strongly-typed objects.
Currently, I have my code structured this way:
String sql = "INSERT INTO problem " + "(name, favorite_number, favorite_color) VALUES (?, ?, ?)";
PreparedStatement ps = c.prepareStatement(sql);
int counter = 1;
while( keys2.hasNext() ) {
String key = (String)keys2.next();
ps.setObject(counter, dataValues.get(key));
counter ++;
}
ps.executeUpdate();
ps.close();
The structure of the target postgres table is:
name: string
favorite_number: int
favorite_color: string
Where dataValues is a JSONObject:
JSONObject dataValues = (JSONObject) configParameters.get(2);
Iterator<?> keys = dataValues.keys();
The JDBC driver fails with the following message:
org.postgresql.util.PSQLException: ERROR: column "favorite_number" is of type integer but expression is of type character varying
Hint: You will need to rewrite or cast the expression.
Is there any way to create this INSERT statement in such a way, that not explicit type cast is needed?
jsondatatype, but that's not really a solution (unless you want to save json data as-is).