2

I am using Spring JdbcTemplates in my project and I want to insert data into an Oracle database. Just after inserting the data I need the ID (sr_no) of this inserted value, so that I can use it.

public int addData(News newsAdd) {
    int flag = 0;

    String url="";
    String cat = newsAdd.getNewsCat();
    String language = newsAdd.getNewsLang();

    // QueryConstant.newsArbian ="INSERT INTO INTERNET_NEWS(SR_NO,TITLE,NEWS_STATUS,HOME_DISPLAY,HOME_DESC,MAIN_DESC,NEWS_DATE,NEWS_CAT,IMGNEWS_URL) VALUES(seq_news.nextval,?,?,?,?,?,?,?,?)";

    flag = getJdbcTemplate().update(
        QueryConstant.newsArbian,
        new Object[] {
            newsAdd.getTitle(),
            newsAdd.getStatus(),
            newsAdd.getNewsHomePage(),
            newsAdd.getNewsDesHom(),
            newsAdd.getNewsDesMan(),
            newsAdd.getDate(),
            newsAdd.getNewsCat(),
            url
        }
    );

    return flag;
}

Now, there is the field sr_no in the table which is auto increment. I want to fetch the value of sr_no of the data that I inserted and pass this value to the flag variable.

How can I achieve this task?

Antti29
  • 2,953
  • 12
  • 34
  • 36
007
  • 115
  • 1
  • 13
  • 1
    duplicate? http://stackoverflow.com/questions/1665846/identity-from-sql-insert-via-jdbctemplate – hahn Mar 21 '16 at 08:59
  • Does this answer your question? [identity from sql insert via jdbctemplate](https://stackoverflow.com/questions/1665846/identity-from-sql-insert-via-jdbctemplate) – Deepak Oct 12 '20 at 09:03

2 Answers2

0

You can use KeyHolder class for this. Check out the section 13.5.2 Retrieving auto-generated keys using SimpleJdbcInsert on this link http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/jdbc.html#jdbc-simple-jdbc-insert-2

Lokesh
  • 7,810
  • 6
  • 48
  • 78
0

try GeneratedKeyHolder [docs]:(https://docs.spring.io/spring/docs/2.5.6/javadoc-api/org/springframework/jdbc/support/GeneratedKeyHolder.html) It will return the auto-generated ID of last inserted record.