go to the link :
https://www.devglan.com/spring-jdbc/fetch-auto-generated-primary-key-value-after-insert-spring-jdbc
to show this code
package com.domain.ecommerce.customer.user;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
public class JdbcTemplateImpl {
private final String INSERT_SQL = "INSERT INTO USERS(name,address,email) values(?,?,?)";
@Autowired
private JdbcTemplate jdbcTemplate;
public User create(final User user) {
KeyHolder holder = new GeneratedKeyHolder();
PreparedStatementCreator psc = new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(INSERT_SQL, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, user.getName());
ps.setString(2, user.getFullName());
ps.setString(3, user.getEmail());
return ps;
}
};
jdbcTemplate.update(psc, holder);
int newUserId = holder.getKey().intValue();
user.setId(newUserId);
return user;
}
}