0

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

Sahap Asci
  • 773
  • 7
  • 10
Vasek
  • 3
  • 2
  • I am not an expert, but to my understanding you get the data from the database as string. As such, you could run your serialized list through a parser (something as simple as 'split' might already do and you'll get your list back. – Refugnic Eternium Feb 08 '23 at 06:21

2 Answers2

0

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

  • Thanks for comment. Not sure, I have compilation error. "Required type List, provided Object" – Vasek Feb 08 '23 at 13:25
0

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();
Vasek
  • 3
  • 2