Win a copy of Head First Android this week in the Android forum!

Ahmed Ramadan

Greenhorn
+ Follow
since Oct 27, 2018
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Ahmed Ramadan

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;
}

}