Role.java
package kr.or.connect.daoexam.dto;
public class Role {
private int roleId;
private String description;
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override //toString 메소드를 오버라이딩 하여 객체의 값들을 한번에 보여줄 수 있도록 함
public String toString() {
return "Role [roleId=" + roleId + ", description=" + description + "]";
}
}
RoleDaoSqls.java
package kr.or.connect.daoexam.dao;
public class RoleDaoSqls {
public static final String SELECT_ALL="SELECT role_id, description FROM role order by role_id";
}
RoleDao.java
package kr.or.connect.daoexam.dao;
import java.util.Collections;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import kr.or.connect.daoexam.dto.Role;
import static kr.or.connect.daoexam.dao.RoleDaoSqls.*;
@Repository //DAO에는 저장소의 역할을 한다는 의미로 Repository 어노테이션을 붙임
public class RoleDao {
private NamedParameterJdbcTemplate jdbc;
// 이름을 이용해 바인딩, 결과값 가져올 수 있음
// role_id, roleId와 같이 규칙이 다른 이름을 자동으로 매핑
private RowMapper<Role> rowMapper = BeanPropertyRowMapper.newInstance(Role.class);
public RoleDao(DataSource dataSource) {
this.jdbc = new NamedParameterJdbcTemplate(dataSource);
}
public List<Role> selectAll(){
// RoleDaoSqls에서 가져온 SELECT_ALL 쿼리문을 실행시켜 rowMapper에 저장하게 됨
return jdbc.query(SELECT_ALL, Collections.emptyMap(), rowMapper);
}
}
ApplicationConfig.java
@ComponentScan(basePackages= {"kr.or.connect.daoexam.dao"})
package kr.or.connect.daoexam.main;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import kr.or.connect.daoexam.config.ApplicationConfig;
import kr.or.connect.daoexam.dao.RoleDao;
import kr.or.connect.daoexam.dto.Role;
public class SelectAllTest {
public static void main(String[] args) {
ApplicationContext ac = new AnnotationConfigApplicationContext(ApplicationConfig.class);
RoleDao roleDao = ac.getBean(RoleDao.class);
List<Role> list = roleDao.selectAll();
for(Role role: list) {
System.out.println(role);
}
}
}