1

I have below code in place where I am trying to get only 1 column (JSON type) from postgres DB and map it to a POJO class. But, in the result I am getting correct count but with null values only, even though data is present. Any Help/Suggestion is appreciated.

POJO Class:

@JsonIgnoreProperties(ignoreUnknown = true)
public class EmployeePayload {

    private String empName;

    private String empID;

   //getters and setters
}

Query Execution Code ::

String query = "SELECT emp_payload FROM EmpDetails";
ResultSetHandler<List<EmployeePayload>> employeePayload = new BeanListHandler<EmployeePayload>(EmployeePayload.class);
        List<EmployeePayload> resultList = runner.query(dbConnection, query, employeePayload);

        log.info(":: resultList is :: " + resultList);

Data in DB ::

"{""empName"":""james"",""empID"":""008""}", "{""empName"":""bond"",""empID"":""007""}"

Result in Log ::

resultList is :: [EmployeePayload{empName='null', empID='null'}, EmployeePayload{empName='null', empID='null'}]

1 Answer 1

2

The BeanListHandler comes from apache dbutils (docs)

By looking at the docs / source, it's implemented by mapping single columns to single properties of the Bean. You are essentially trying to map a single column to multiple properties which does not work. Now there are two ways to go about this:

  1. Writing your own RowProcessor
  2. Rewriting the query to return multiple columns.

In this situation I would favor the second solution for it's simplicity as postgres has this functionality built-in for its json field types.

Your query could look like this:

String query = "SELECT emp_payload->'empName' AS empName, emp_payload->'empID' AS empID FROM EmpDetails";

(The AS ... might not be necessary but I don't know how psql generates the column names for extracted json values).

If you would execute this query directly in postgres, you would get a result set with column names empName and empID which is exactly what the BeanProcessor (the default processor for BeanListHandler) expects.

Sign up to request clarification or add additional context in comments.

1 Comment

I went with the second solution, Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.