-
카테고리
-
세부 분야
백엔드
-
해결 여부
미해결
@Repository 사용 차이점
24.03.18 22:07 작성 조회수 138
0
안녕하세요
강의 중에 MyBatisItemRepository는 @Repository가 있고
Jdbc관련 Repository에는 애너테이션이 안 붙여져 있는데 그 이유가 무엇인가요?
답변을 작성해보세요.
2
김영한
지식공유자2024.03.19
안녕하세요. III님
@Repository를 사용하면 JDBC 예외를 스프링의 데이터 계층 예외로 변환해주는 AOP가 적용됩니다.
그런데 스프링이 제공하는 JdbcTemplate은 JDBC 예외를 스프링의 데이터 계층 예외로 변환해주는 기능을 내부에 포함하고 있습니다. 따라서 JdbcTemplate을 사용할 대는 @Repository를 사용하지 않았습니다.
감사합니다.
1
y2gcoder
2024.03.19
안녕하세요. lll님, 공식 서포터즈 y2gcoder입니다.
죄송합니다! @Repository 애노테이션이 붙어있지 않은 Jdbc 관련 Repository 구현체 클래스를 찾지 못했습니다...
혹시 어디서 확인하셨는지 알려주신다면 답변을 드리는데 도움이 될 것 같습니다
감사합니다.
III
질문자2024.03.19
@Slf4j
public class JdbcTemplateItemRepositoryV3 implements ItemRepository {
// private final JdbcTemplate template;
private final NamedParameterJdbcTemplate template;
private final SimpleJdbcInsert jdbcInsert;
public JdbcTemplateItemRepositoryV3(DataSource dataSource) {
this.template = new NamedParameterJdbcTemplate(dataSource);
this.jdbcInsert = new SimpleJdbcInsert(dataSource)
.withTableName("item")
.usingGeneratedKeyColumns("id");
}
@Override
public Item save(Item item) {
SqlParameterSource param = new BeanPropertySqlParameterSource(item);
Number key = jdbcInsert.executeAndReturnKey(param);
item.setId(key.longValue());
return item;
}
@Override
public void update(Long itemId, ItemUpdateDto updateParam) {
String sql = "update item " +
"set item_name=:itemName, price=:price, quantity=:quantity " +
"where id=:id";
SqlParameterSource param = new MapSqlParameterSource()
.addValue("itemName", updateParam.getItemName())
.addValue("price", updateParam.getPrice())
.addValue("quantity", updateParam.getQuantity())
.addValue("id", itemId);
template.update(sql, param);
}
@Override
public Optional<Item> findById(Long id) {
String sql = "select id, item_name, price, quantity from item where id=:id";
try {
Map<String, Object> param = Map.of("id", id);
Item item = template.queryForObject(sql, param, itemRowMapper());
return Optional.of(item);
} catch (EmptyResultDataAccessException e) {
return Optional.empty();
}
}
private RowMapper<Item> itemRowMapper() {
return BeanPropertyRowMapper.newInstance(Item.class);
}
@Override
public List<Item> findAll(ItemSearchCond cond) {
String itemName = cond.getItemName();
Integer maxPrice = cond.getMaxPrice();
SqlParameterSource param = new BeanPropertySqlParameterSource(cond);
String sql = "select id, item_name as itemName, price, quantity from item";
//동적 쿼리
if (StringUtils.hasText(itemName) || maxPrice != null) {
sql += " where";
}
boolean andFlag = false;
if (StringUtils.hasText(itemName)) {
sql += " item_name like concat('%',:itemName,'%')";
andFlag = true;
}
if (maxPrice != null) {
if (andFlag) {
sql += " and";
}
sql += " price <= :maxPrice";
}
log.info("sql={}", sql);
return template.query(sql, param, itemRowMapper());
}
}
이 클래스입니다
답변 2