Wednesday, July 19, 2017

Spring 4 Jdbc Template CRUD

How to use Jdbc Template in Spring MVC application using Java Config

You can download source code from Spring4JdbcTemplate

@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.setResultsMapCaseInsensitive(true);
return jdbcTemplate;
}

@Bean
public PlatformTransactionManager txManager() {
return new DataSourceTransactionManager(dataSource());
}


public interface EmployeeDao {
public void save(Employee employee);
public void update(Employee employee, Integer id);
public void delete(Integer id);
public Employee get(Integer id);
public List<Employee> list();
}


 
@Repository
@Transactional
public class EmployeeDaoImpl implements EmployeeDao {

@Autowired
JdbcTemplate jdbcTemplate;

@Override
public void save(Employee employee) {
jdbcTemplate.update("INSERT INTO employee (id, firstName, lastName,email) VALUES (?, ?, ?, ?)",
employee.getId(), employee.getFirstName(), employee.getLastName(), employee.getEmail());
System.out.println("Employee Save!!");
}

@Override
public void update(Employee employee, Integer id) {
jdbcTemplate.update("UPDATE employee SET firstName = ? , lastName = ? , email = ? WHERE id = ? ",
employee.getFirstName(), employee.getLastName(), employee.getEmail(), id);
System.out.println("Employee Updated!!");

}

@Override
public void delete(Integer id) {
jdbcTemplate.update("DELETE from employee WHERE id = ? ", id);
System.out.println("Employee Deleted!!");
}

@SuppressWarnings("unchecked")
@Override
public Employee get(Integer id) {
@SuppressWarnings("rawtypes")
Employee employee = (Employee) jdbcTemplate.queryForObject("SELECT * FROM employee where id = ? ",
new Object[] { id }, new BeanPropertyRowMapper(Employee.class));
return employee;
}

@SuppressWarnings("unchecked")
@Override
public List<Employee> list() {
@SuppressWarnings("rawtypes")
List<Employee> employees = jdbcTemplate.query("SELECT * FROM employee",
new BeanPropertyRowMapper(Employee.class));
return employees;
}

}

No comments:

Post a Comment