How to get the ID after inserting data into an Oracle database with Spring JdbcTemplates

advertisements

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?


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