Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ua.epam.kiev.rd.springproject.repository; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import ua.epam.kiev.rd.springproject.domain.City; /** * * @author Shiwa */ @Repository("jdbcCityRepository") public class JdbcCityRepository implements CityRepository { private JdbcTemplate jdbcTemplate; @Autowired public JdbcCityRepository(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public Collection<City> getAllCities() { try { return this.jdbcTemplate.query("select CityID, name from city", new CityMapper()); } catch (DataAccessException e) { Logger.getLogger(JdbcCityRepository.class.getName()).log(Level.SEVERE, null, e); return null; } } public boolean create(City city) { int queryResult = jdbcTemplate.update("insert into City(Name) values(?)", city.getName()); return queryResult > 0; } public boolean update(City city) { int queryResult = jdbcTemplate.update("update City set Name = ? where CityID = ?", city.getName(), city.getId()); return queryResult > 0; } public boolean delete(City city) { int queryResult = jdbcTemplate.update("delete from City where CityID = ?", city.getId()); return queryResult > 0; } public City getCityByID(int id) { try { City city = jdbcTemplate.queryForObject("select CityID, Name from City where CityID = ?", new CityMapper(), id); return city; } catch (DataAccessException e) { Logger.getLogger(JdbcCityRepository.class.getName()).log(Level.SEVERE, null, e); return null; } } private static class CityMapper implements RowMapper<City> { public City mapRow(ResultSet rs, int rowNum) throws SQLException { City city = new City(); city.setId(rs.getInt("CityID")); city.setName(rs.getString("Name")); return city; } } }