Search code examples
postgresqlspring-jdbcjdbctemplate

How to get the value of any column of a row inserted with JdbcTemplate


Can I use Spring's JdbcTemplate to get a column value of a row just inserted?

E.g. the SQL looks so:

insert into table1 (name, age) values ('name', 20) returning name;

And I want to get the value of the name column.

The update() method returns the number of inserted rows only.


Solution

  • It looks like you can insert rows if you use JdbcTemplate.queryForObject() and the sql uses with ... as construct:

    String sql="with result as (\n" +
            "insert into table1 (name, age) values ('name', 20) returning name\n" +
            ")\n" +
            "select name from result;";
    
    String name = jdbcTemplate.queryForObject(sql, String.class);