skip to Main Content

I have following class:

public class Person {

 private String firstName;
 private String lastName;
 private List<String> habits;
}

I have Postgres query which returns me following result using inner join from 2 tables

name | lastname|      habits
--------------------------------------      
John | Smith   | ["walking", "eating"]

I am trying to write RowMapper as following:

private final RowMapper<Person> rowMapper = (rs, rowNum) -> {

 String firstName = rs.getString("name");
 String lastName =  rs.getString("lastName");
}

I am not sure how to create List habits from "habits column in my result table"

Please advise

Thanks

2

Answers


  1. Chosen as BEST ANSWER

    Found an answer

    The code below is working fine

    String[] habits;
            try {
                habits = objectMapper.readValue(rs.getString("habits"), String[].class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            List<String> habitsList = Arrays.stream(habits).toList();
    

  2. I have tried it and working fine. You can try the below code what I have understand from your description.

    String firstName = rs.getString("name");
    String lastName =  rs.getString("lastName");
    List<String> list  =  rs.getObject("habits");
    

    if you get compilation error, it will work definitly

    List stringList = new ArrayList;
    List objectList = stringList;// this does compile only if List where subtypes of List
    objectList.add(new Object());
    String s = stringList.get(0);

    it should work.
    Let me know if you facing still issue

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search