티스토리 뷰

JAVA/Spring

[Spring] RowMapper

stdbc 2019. 10. 12. 01:00

#DTO, DAO

#DAO (JDBC Template)


RowMapper

DB의 컬럼명과 클래스의 필드명이 다른 경우 생성 (보통 JOIN TABLE)

cf) DB의 컬럼명과 클래스의 필드명이 같은 경우: #BeanPropertyRowMapper

 

1
2
3
4
5
6
7
8
9
10
11
12
public class RoleMapper implements RowMapper<Role> {
 
    @Override
    public Role mapRow(ResultSet rs, int rowNum) throws SQLException {
        
       Role role = new role();
       role.setRoleId(rs.getInt(1));
       role.setDescription(rs.getString(2));
        
        return role;
    }
}
cs

line 4 mapRow: 행의 수만큼 호출된다. (한 번만 호출되는 것이 아님)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Repository
public class RoleDao {
    private NamedParameterJdbcTemplate jdbc;
/*    private RowMapper<Role> rowMapper = BeanPropertyRowMapper.newInstance(Role.class); */
 
    public RoleDao(DataSource dataSource) {
        this.jdbc = new NamedParameterJdbcTemplate(dataSource);
    }
    
    public List<Role> selectRoleAll(){
        String SELECT_ALL = "SELECT role_id, description FROM role ORDER BY role_id";
        return jdbc.query(SELECT_ALL, Collections.emptyMap(), /*rowMapper*/ new RoleMapper());
    }
 
}
 
cs

line 4, 12: BeanPropertyRowMapper 사용할 때와 차이

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함