package org.pegadi.server.department;
import org.pegadi.model.Section;
import org.pegadi.server.SectionServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* User: jan-preben
* Date: Sep 22, 2010
*/
public class SectionServerImpl implements SectionServer {
private Logger log = LoggerFactory.getLogger(getClass());
private JdbcTemplate template;
private DepartmentRowMapper departmentMapper;
public SectionServerImpl() {
departmentMapper = new DepartmentRowMapper();
}
public void setDataSource(DataSource dataSource) {
this.template = new JdbcTemplate(dataSource);
}
/**
* Returns the department with the given ID
*
* @param ID the ID of the department
* @return an department, or null if no department found
*/
@Cacheable("Department")
public Section getDepartment(int ID) {
if (ID == 0) {
return null;
}
try {
return template.queryForObject("SELECT * FROM Section WHERE ID=?", departmentMapper, ID);
} catch (EmptyResultDataAccessException e) {
log.info("No department with found with Id: "+ ID);
return null;
}
}
/**
* Returns all available departments
*
* @return an array of <code>Section</code>s.
*/
@Cacheable("Section")
public List<Section> getDepartments() {
return template.query("SELECT * FROM Section", departmentMapper);
}
private class DepartmentRowMapper implements ParameterizedRowMapper<Section> {
public Section mapRow(ResultSet rs, int rowNum) throws SQLException {
Section section = new Section(rs.getInt("ID"));
section.setDescription(rs.getString("description"));
section.setName(rs.getString("name"));
return section;
}
}
}