package com.example.demo;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.example.demo.Team;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport; // 스프링 JDBC를 사용해서 데이터베이스 접근
import com.example.demo.TeamDao;
// JdbcDaoSupport 클래스 상속
// TeamDao 인터페이스 구현
public class TeamDaoImpl extends JdbcDaoSupport implements TeamDao {
public List<Team> getTeamList() throws DataAccessException {
// 콜백 인터페이스 생성
// RowMapper 인터페이스를 구현한 클래스(TeamRowMapper)의 인스턴스 생성
RowMapper<Team> rowMapper = new TeamRowMapper();
// SQL 실행, SQL 구문과 TeamRowMapper 인스턴스를 인수로 넘김
// mapRow() 메서드를 스프링이 호출 --> 콜백처리, rowMapper를 콜백 인터페이스
// 스프링이 next() 메서드를 호출하고, 루프 회수만큼 스프링이 mapRow() 메서드 호출
return getJdbcTemplate().query("SELECT team_id, name FROM team", rowMapper);
}
// TeamRowMapper 구현
protected class TeamRowMapper implements RowMapper<Team> {
private List<Team> teamList = new ArrayList<Team>();
public List<Team> getResults() {
return teamList;
}
@Override // RowMapper<Team>의 mapRow 인터페이스 구현
public Team mapRow(ResultSet rs, int rowNum) throws SQLException {
// ResultSet에서 취득한 값을 객체에 넣기
Team team = new Team();
team.setId(rs.getInt("team_id"));
team.setName(rs.getString("name"));
return team;
}
}
}
- DB 테이블에 접근하는 메서드를 호출하는 클래스는 DAO Interface를 통해 호출
- 이렇게 함으로써, 호출하는 쪽 클래스와 실제로 데이터베이스에 접근하는 구현 클래스와의 직접적인 의존을 느슨하게
- DAO Implementation 클래스에만 데이터베이스 접근 코드를 기술해서 DB 연결이나, SQL 데이터베이스 구문이 다른 클래스에 산재하지 않고, 한곳에서 관리하는 것이 가능
- JdbcDaoSupport 클래스는 JdbcTemplate 클래스를 취득하기 위한 getJdbcTemplate() 메서드를 구현
- 스프링 설정 파일(applicationContext.xml)에서 DAO Implementation 클래스에 데이터소스를 의존 관계를 주입하는데 setDataSource() 메서드가 JdbcDaoSupport 클래스에 정의되어 있음
'Programming > Java' 카테고리의 다른 글
STS에서 Data Source Explorer가 안보일 때 (0) | 2020.03.22 |
---|---|
Attribute 'local' is not allowed to appear in element 'ref'. (0) | 2020.03.22 |
Spring AOP(Aspect Oriented Programming) Sample (0) | 2020.03.22 |
STS 4에서 Spring Legacy Project 사용 및 설정 (0) | 2020.03.12 |
Spring STS 4 설치 (0) | 2020.03.12 |