2016-04-20 68 views
0

我使用spring框架,並且想要向DB插入一行以獲得其ID,這是進一步處理所需的。 插入查詢如下,它是一個簡單的查詢,沒有參數。但更糟的是,如何使用executeAndReturnKeySimpleJdbcInsert構建工作呼叫?這是插入的SQL查詢。但我不知道在simpleJdbcInsert實例中是否可以使用它。如何在春季向DB插入一行,僅使用自動生成的值並返回一個ID?

insert into sdc_import_run(id_import_run, create_date) 
values(nextval('seq_import_run'),now()) 

我試圖

Number genId = simpleJdbcInsert.withTableName("sdc_import_run") 
      .usingGeneratedKeyColumns("id_import_run") 
      .executeAndReturnKey(new MapSqlParameterSource()); 

它不工作,問題是,他們想表的所有參數,但我不想任何人,我想自動生成,只插入:id_import_run(主鍵)和create_date。因此我想要在變量中插入ID。你會怎麼做?

編輯 這種方法工作正常。

public Integer persistInsertImportRunForId(){ 
    String queryString = getSql("insertImportRunForId"); 
    KeyHolder holder = new GeneratedKeyHolder(); 
    jdbcTemplate.update(con -> { 
      return con.prepareStatement(queryString, Statement.RETURN_GENERATED_KEYS); 
     }, holder 
    ); 

    return CommonUtils.tryOrGet(() -> holder.getKeys().get("id_import_run"), null); 
} 

回答

1

您可以使用JdbcTemplate運行完整的插入SQL。你可以在這裏提供你想要的任何SQL,只要你的表的DDL允許,爲你的插入定義少量或多個列。

This answer涵蓋了更多細節。

相關問題