2017-09-23 118 views
0

我想從postgres數據庫中獲取插入ID。我的代碼現在看起來像:如何從數據庫中獲取插入ID?春季啓動

String sql = "INSERT INTO ACCOUNT (name) VALUES (?);"; 
     jdbcTemplate.update(sql, account.name); 

id是自動生成的。

我應該如何更改此代碼,它會返回插入帳戶的行ID?

+0

看起來像[this](https://stackoverflow.com/a/16061409/7940179)答案可能會幫助你 – EmberTraveller

回答

0

您可以使用SimpleJdbcInsert插入值並從操作中獲取生成的密鑰。

public class JdbcActorDao implements ActorDao { 

private JdbcTemplate jdbcTemplate; 
private SimpleJdbcInsert insertActor; 

public void setDataSource(DataSource dataSource) { 
    this.jdbcTemplate = new JdbcTemplate(dataSource); 
    this.insertActor = new SimpleJdbcInsert(dataSource) 
      .withTableName("t_actor") 
      .usingGeneratedKeyColumns("id"); 
} 

public void add(Actor actor) { 
    Map<String, Object> parameters = new HashMap<String, Object>(2); 
    parameters.put("first_name", actor.getFirstName()); 
    parameters.put("last_name", actor.getLastName()); 
    Number newId = insertActor.executeAndReturnKey(parameters); 
    actor.setId(newId.longValue()); 
} 
}