@Repository 사용 차이점
361
작성한 질문수 21
안녕하세요
강의 중에 MyBatisItemRepository는 @Repository가 있고
Jdbc관련 Repository에는 애너테이션이 안 붙여져 있는데 그 이유가 무엇인가요?
답변 2
2
안녕하세요. III님
@Repository를 사용하면 JDBC 예외를 스프링의 데이터 계층 예외로 변환해주는 AOP가 적용됩니다.
그런데 스프링이 제공하는 JdbcTemplate은 JDBC 예외를 스프링의 데이터 계층 예외로 변환해주는 기능을 내부에 포함하고 있습니다. 따라서 JdbcTemplate을 사용할 대는 @Repository를 사용하지 않았습니다.
감사합니다.
1
안녕하세요. lll님, 공식 서포터즈 y2gcoder입니다.
죄송합니다! @Repository 애노테이션이 붙어있지 않은 Jdbc 관련 Repository 구현체 클래스를 찾지 못했습니다...
혹시 어디서 확인하셨는지 알려주신다면 답변을 드리는데 도움이 될 것 같습니다 



감사합니다.
1
@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());
}
}
이 클래스입니다
RepositoryTest의 패키지 위치가 domain인 이유
0
29
2
REQUIRES_NEW 해결 방법에 대해서 질문있습니다!!
0
29
1
update()에 사용하는 setter 질문드립니다.
0
47
1
SQL 중심적 개발의 문제점에 대한 질문
0
72
1
혹시 Containing 을 안쓰신 이유가 있을까요?
0
83
2
[공유] 스프링부트 4.x 버전 mybatis 연동
0
173
1
@repository 어노테이션
0
89
3
ItemService
0
58
1
논리 커밋, 물리 커밋 질문드립니다.
0
54
1
내부 트랜잭션 커밋은 필수인가요?
0
57
1
프록시 커넥션 객체를 반환할 때 생성하는건가요?
0
54
1
Transaction readOnly 성능 개선 (김영한님의 대한 감사인사)
2
178
2
JPQL 대신 네이티브 쿼리를 사용해야 하는 경우
0
77
1
@EventListener(ApplicationReadyEvent.class) 관련
0
88
1
트랜잭션 동기화 매니저와 데이터 소스
0
76
1
DB 관련 강의 개설 계획은 없으신건가요?
0
133
2
물리 트랜잭션 과 논리트랜잭션 용어를 맞게 이해한걸까요
0
94
1
스프링 3 버전 이상 rollbackFor 변경된듯요
1
112
1
트랜잭션 전파 질문.
0
87
1
프로젝트 오픈 에러
0
126
1
외부 트랜잭션에서 isNewTransaction이 false로 나오는거에 대해 질문드립니다
0
83
2
같은 스레드를 사용하면 트랜잭션 동기화 매니저는 같은 커넥션을 반환
0
72
1
h2 인메모리 테스트중 예약어 충돌날 경우 대처방법
0
102
1
커스텀aop와 트랜잭션을 같이 사용할때 우선순위에 관한 질문
0
98
2





