2012-10-14 73 views
11
private void insertIntoMyTable (Myclass m) { 
    String query = "INSERT INTO MYTABLE (NAME) VALUES (?)"; 
    jdbcTemplate.update(query, m.getName()); 
} 

在表中插入一條記錄,當上面的查詢中插入一條記錄,在表中自動遞增的ID列。我怎樣才能獲得自動遞增的ID,當我通過JdbcTemplate的

有沒有辦法在插入時得到這個自動遞增的ID。因此,在這個例子中我的方法的返回值將是int

+0

我想你可能只是在一個事務中插入後需要一個選擇。 – PbxMan

回答

15

檢查this reference.您可以使用jdbcTemplate.update爲:

編輯 增加進口的要求

import java.sql.Connection; 
import java.sql.PreparedStatement; 
import java.sql.SQLException; 

import org.springframework.jdbc.core.JdbcTemplate; 
import org.springframework.jdbc.core.PreparedStatementCreator; 
import org.springframework.jdbc.support.GeneratedKeyHolder; 
import org.springframework.jdbc.support.KeyHolder; 

以下是代碼用法:

final String INSERT_SQL = "insert into my_test (name) values(?)"; 
final String name = "Rob"; 
KeyHolder keyHolder = new GeneratedKeyHolder(); 
jdbcTemplate.update(
    new PreparedStatementCreator() { 
     public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { 
      PreparedStatement ps = 
       connection.prepareStatement(INSERT_SQL, new String[] {"id"}); 
      ps.setString(1, name); 
      return ps; 
     } 
    }, 
    keyHolder); 
// keyHolder.getKey() now contains the generated key 
+0

這只是在MySql的權利? – PbxMan

+0

我還沒有測試過自己,但應該與mysql – Anshu

+0

一起工作,請你把進口? – PbxMan

1

我得到數據庫生成的id ASE(MSSQL)像下面插入後,進口:

import org.springframework.jdbc.core.BeanPropertyRowMapper; 
    import org.springframework.jdbc.core.JdbcTemplate; 
    import org.springframework.jdbc.core.RowMapper; 
    import org.springframework.jdbc.core.SqlParameter; 
    import org.springframework.jdbc.core.SqlReturnResultSet; 
    import org.springframework.jdbc.core.simple.SimpleJdbcCall; 

和代碼片段:

final String INSERT_SQL = "INSERT INTO [table]\n" 
      + " ([column_1]\n" 
      + " ,[column_2])\n" 
      + " VALUES\n" + 
      " (?, ?)"; 

    Connection connection = jdbcTemplate.getDataSource().getConnection(); 
    PreparedStatement preparedStatement = connection.prepareStatement(INSERT_INVOICE_SQL, Statement.RETURN_GENERATED_KEYS); 
    preparedStatement.setString(1, "test 1"); 
    preparedStatement.setString(2, "test 2"); 

    preparedStatement.executeUpdate(); 
    ResultSet keys = preparedStatement.getGeneratedKeys(); 

    if (keys.next()) { 
     Integer generatedId = keys.getInt(1); //id returned after insert execution 
    }