2

I am using spring to interact with postgresql. Here is my problem.

Person have three attributes:

  1. name(String)
  2. hobbies(String[])
  3. gender(boolean)

If I try to get a list of person from database using the method below

List<Person> person=  getJdbcTemplate().query("select * from person where name=?",new BeanPropertyRowMapper<person>(Person.class),name);

The compiler prompts

Failed to convert property value of type 'org.postgresql.jdbc.PgArray' to required type 'java.lang.String[]' for property 'hobbies';

Is there any way to map pgarray to java array?

2 Answers 2

1

By implementing our own RowMapper

public class PersonRowMapper implements RowMapper<Person> {

     Person mapRow(ResultSet rs, int rowNum) throws SQLException {
          Person person = new Person();
          person.setName("nameColumnName");
          person.setGender(rs.getBoolean("genderColumnName"));

          String[] hobbies = (String[]) rs.getArray("hobbies");
          person.setHobbies(hobbies);

          return person;
     }

}

Using the above code, we can manually cast the result of rs.getArray() into String[].

RowMapper helps to provide custom logic to parse the result set into our own object. Use it in place of BeanPropertyRowMapper like below:

List<Person> person = getJdbcTemplate().query("select * from person where name = ?", new PersonRowMapper(), name);
Sign up to request clarification or add additional context in comments.

2 Comments

Please add more explanation
@ManuViswam added full example and description. Thanks for pointing out.
0

I didn't find how to solve the problem with jdbctemplate + pgArray. So I wrote some fix.
You can use own ColumnMapRowMapper.

public class ColumnRawMapper extends ColumnMapRowMapper {
        @Override
        protected Object getColumnValue(ResultSet rs, int index) throws SQLException {
            Object obj = rs.getObject(index);
            if (obj instanceof PgArray) {
                return ((PgArray) obj).getArray();
            }
            return super.getColumnValue(rs, index);
        }
    }

Map<String, Object> ggWp = jdbcTemplate.queryForObject("select * from temp where ss='3'", new ColumnRawMapper());

Comments

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.