Spring/Toby의 스프링3 따라하기

SpringJDBC - BeanPropertyRowMapper

KyeongRok Kim 2021. 12. 22. 11:16

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/core/BeanPropertyRowMapper.html

 

BeanPropertyRowMapper (Spring Framework 5.3.14 API)

RowMapper implementation that converts a row into a new instance of the specified mapped target class. The mapped target class must be a top-level class and it must have a default or no-arg constructor. Column values are mapped based on matching the column

docs.spring.io

BeanPropertyRowMapper를 이용하면 Orm처럼 Pojo Bean을 RowMapper로 바로 만들 수 있습니다.

 

private RowMapper<User> mapper = new RowMapper<User>() {
    @Override
    public User mapRow(ResultSet rs, int rowNum) throws SQLException {
        User user = new User();
        user.setId(rs.getInt("id"));
        user.setName(rs.getString("name"));
        user.setPassword(rs.getString("password"));
        user.setLevel(Level.valueOf(rs.getInt("level")));
        user.setLogin(rs.getInt("login"));
        user.setRecommend(rs.getInt("recommend"));
        return user;
    }
};

위와 같이 직접 매핑 해주던 것을

 

private RowMapper<User> mapper2 = BeanPropertyRowMapper.newInstance(User.class);

 

 

PagingAndSortRepository는 페이징도 제공 해줍니다.

 

그런데 Enum은 처리해주기가 조금 까다롭네요.

 

 

queryForObject관련 내용

토비의스프링3 JdbcTemplate의 queryForObject (tistory.com)

728x90