[NamedParameterJdbcTemplate 사용하기]
NamedParameterJdbcTemplate
- 바인딩시 ? 를 사용하지 않고 :parameter 를 사용
- 세번째 파라미터로 RowMapper<>와 함께 활용
(sql문에 바인딩 할 값이 있을 경우에 바인딩 할 값을 전달할 목적으로 사용하고 있는 객체)
BeanPropertyRowMapper
- column의 값을 자동으로 DTO에 담아주는 객체
- query() 메서드의 반환 값이 여러 건일 때 내부적으로 반복하면서 DTO를 생성후 List에 담아 반환
@Repository | |
public class ProductDao { | |
private NamedParameterJdbcTemplate jdbc; | |
private RowMapper<Product> rowMapper = BeanPropertyRowMapper.newInstance(Product.class); | |
/** | |
* 생성자를 통한 DI주입 | |
* | |
* @param dataSource | |
*/ | |
public ProductDao(DataSource dataSource) { | |
this.jdbc = new NamedParameterJdbcTemplate(dataSource); | |
this.insertAction = new SimpleJdbcInsert(dataSource).withTableName("Product").usingGeneratedKeyColumns("id"); | |
} | |
/** | |
* product 전체 개수 | |
* @return | |
*/ | |
public int selectCount() { | |
System.out.println(); | |
return jdbc.queryForObject(SELECT_TOTAL_COUNT, Collections.emptyMap(), Integer.class); | |
} | |
/** | |
* 데이터 출력 3, 4개씩 | |
* @param start | |
* @return | |
*/ | |
public List<Product> selectAll(Integer start) { | |
Map<String, Integer> paramMap = new HashMap<>(); | |
paramMap.put("start", start); | |
paramMap.put("limit", 4); | |
return jdbc.query(SELECT_PRODUCT_MORE, paramMap, rowMapper); | |
} | |
/** | |
* 데이터 하나만 출력 | |
* @param id | |
* @return | |
*/ | |
public Product selectItem(Integer id) { | |
return jdbc.queryForObject(SELECT_PRODUCT_ONE, new MapSqlParameterSource("id", id), rowMapper); | |
} | |
/** | |
* 카테고리, 상품 목록 구하기 | |
* @param category_id | |
* @param start | |
* @param limit | |
* @return | |
*/ | |
public List<Product> selectCategoryAll(Integer category_id, Integer start) { | |
Map<String, Integer> paramMap = new HashMap<>(); | |
paramMap.put("category_id", category_id); | |
paramMap.put("start", start); | |
paramMap.put("limit", 4); | |
return jdbc.query(SELECT_CATEGORY_PRODUCT_LIST, paramMap, rowMapper); | |
} | |
} |
'Spring > Spring Basic' 카테고리의 다른 글
[Spring Study] 코드로 배우는 스프링 웹 프로젝트 (0) | 2018.01.07 |
---|