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

के माध्यम से एक तालिका में एक रिकॉर्ड डालते हैं तो ऊपर क्वेरी एक रिकॉर्ड, टेबल autoincrements में ID स्तंभ सम्मिलित करता है मैं autoincremented आईडी प्राप्त कर सकते हैं।कैसे जब मैं jdbctemplate

क्या इस ऑटो वृद्धि आईडी को सम्मिलन के समय वापस पाने का कोई तरीका है। तो इस उदाहरण में मेरी विधि की वापसी मान होगा 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

मुझे डेटाबेस द्वारा उत्पन्न आईडी मिलती है 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 
    }