简体   繁体   中英

Java Spring Insert Arraylist into postgresql database JdbcTemplate

I need to make a rest application using Spring and PostgreSQL as Database.I need to input into the database some object that contains an ArrayList of String : ArrayList < String >. My problem is that i cant find a way to set my arraylist into preparedStatement. I tried with setObject but it obviously doesn't work. It goes as follow :

public int insert(Location location) {
        return jdbcTemplate.update(conn -> {
            PreparedStatement ps = conn.prepareStatement(INSERT_STMT);
            ps.setInt(1, location.getParam1());
            ps.setString(2, location.getParam2());
            ps.setString(3, location.getParam3());
            ps.setString(4, location.getParam4());
            ps.setString(5, location.getParam5());
            ps.setString(6, location.getParam6());
            ps.setString(7, location.getParam7());
            ps.setObject(8, location.getArrayListDate());
            return ps;
        });
    }
private static final String INSERT_STMT =
        " insert into locations (param1, param2, param3, param4, param5, param6, param7, dates)"
                + " values (?, ?, ?, ?, ?, ?, ?, ?)"
        ;

The table form :

create table locations (
    param1 int primary key
  , param2 text
  , param3 text
  , param4 text
  , param5 text
  , param6 text
  , param7 text
  , dates TEXT[]
)

How can i make this work? Thank you :)

You need to convert java.util.ArrayList to java.sql.Array using conn.createArrayOf() and pass it as

pstmt.setArray("text", array)

Refer this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM