1. Primary Key로 조회하기
기본 문법은 간단:
User user = userMapper.selectByPk(userId);
근데 이렇게만 쓰면 NullPointerException 위험이 있음. 항상 null 체크 해주자.
// 내가 자주 쓰는 패턴
User user = userMapper.selectByPk(userId);
if (user == null) {
throw new EntityNotFoundException("해당 유저 없음");
}
2. MyBatis vs JPA 차이점
MyBatis 쓸 때:
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE user_id = #{userId}")
User selectByPk(@Param("userId") Long userId);
}
JPA로 바꾸면:
// Optional 써서 더 안전하게 처리 가능
Optional<User> user = userRepository.findById(userId);
User foundUser = user.orElseThrow(() ->
new EntityNotFoundException("유저 없음"));
JPA가 확실히 null 처리는 더 깔끔한듯.
3. 실수했던 것들 메모
1. 제일 많이 한 실수: 중복 조회
// ❌ 이렇게 했다가 쿼리 두 번 나감
if (userMapper.selectByPk(userId) != null) {
User user = userMapper.selectByPk(userId); // 또 조회함
processUser(user);
}
// ⭕ 수정한 버전
User user = userMapper.selectByPk(userId);
if (user != null) {
processUser(user);
}
2. 연관 데이터 조회할 때 실수
// ❌ NPE 위험 있는 코드
Order order = orderMapper.selectByPk(orderId);
User user = userMapper.selectByPk(order.getUserId()); // order가 null이면?
// ⭕ 안전하게 수정
Order order = orderMapper.selectByPk(orderId);
if (order != null) {
User user = userMapper.selectByPk(order.getUserId());
// 처리
}
✅ 메모
- PK로 조회할 때는 무조건 null 체크부터
- 조회 결과는 변수에 담아두고 재사용하기
- JPA 쓸 때는 Optional 활용하기
- 연관 데이터 조회할 때는 단계별로 null 체크
이거 까먹으면 또 NPE 만날 것 같으니까 북마크해두자...
'개발노트 > Spring' 카테고리의 다른 글
[Spring] Security 인증(Authentication) 흐름 정리 (1) | 2025.02.18 |
---|---|
[Spring Boot + Vue.js 시리즈 2편] STS4와 Vue.js 연동하기 (1) | 2025.02.14 |
[Spring] 폼 처리와 다국어 정리 (0) | 2025.01.09 |
[Spring] SiteMesh - decorators.xml로 공통 레이아웃 관리 (0) | 2025.01.02 |