Interview Questions

Spring Jdbc - NamedParameterJdbcTemplate

Here is a sample code to perform DB operation using NamedParameterJdbcTemplate API in Spring

Spring Jdbc - NamedParameterJdbcTemplate:

public class UserDao {
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public void createUser(User user) {
                Long userId =1001; //should be generated from a DB sequece
                String insertUserSql = "INSERT INTO DSM_USERS (USER_ID,LOGIN,PASSWORD,FIRST_NAME,"
                                + "LAST_NAME,PHONE_NUMBER,EMAIL,"
                                + "CREATED_DATE,GROUP_ID)"
                                + "  VALUES (:id,:username,:password,:firstName,:lastName,"
                namedParameterJdbcTemplate.update(insertUserSql, new BeanPropertySqlParameterSource(user));

The above class contains createUser method, to insert user details in to DB. Instead of using '?' pointer for the db column values, we are directly using the bean property names for example ":username".