public class EmployeeDaoImpl implements EmpDao { private SimpleJdbcTemplate simpleJdbcTemplate; private SimpleJdbcInsert insertEmp; public void setDataSource(DataSource dataSource) { this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); this.insertEmp = new SimpleJdbcInsert(dataSource).withTableName("employee"); } public void create(String name, Integer age, Long salary) { Map parameters = new HashMap(); parameters.put("name", name); parameters.put("age", age); parameters.put("salary", salary); insertEmp.execute(parameters); } // ... additional methods }The execute method used here takes a plain java.utils.Map as its only parameter. The important thing to note here is that the keys used for the Map must match the column names of the table as defined in the database. This is because we read the metadata in order to construct the actual insert statement.
public class EmployeeDaoImpl implements EmpDao { private SimpleJdbcTemplate simpleJdbcTemplate; private SimpleJdbcInsert insertEmp; public void setDataSource(DataSource dataSource) { this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); this.insertEmp = new SimpleJdbcInsert(dataSource) .withTableName("employee"); .usingGeneratedKeyColumns("empid"); } public void create(String name, Integer age, Long salary) { Map parameters = new HashMap(); parameters.put("name", name); parameters.put("age", age); parameters.put("salary", salary); Number empid = insertEmp.executeAndReturnKey(parameters); } // ... additional methods }3. Specifying columns for a SimpleJdbcInsert:-
public class EmployeeDaoImpl implements EmpDao { private SimpleJdbcTemplate simpleJdbcTemplate; private SimpleJdbcInsert insertEmp; public void setDataSource(DataSource dataSource) { this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); this.insertEmp = new SimpleJdbcInsert(dataSource) .withTableName("employee"); .usingColumns("name", "age", "salary") .usingGeneratedKeyColumns("empid"); } public void create(String name, Integer age, Long salary) { Map parameters = new HashMap(); parameters.put("name", name); parameters.put("age", age); parameters.put("salary", salary); Number empid = insertEmp.executeAndReturnKey(parameters); } // ... additional methods }
Labels: Spring3.0