Foreign Key Validation Without Relying on DataIntegrityViolationException
Foreign Key Validation Without Relying on DataIntegrityViolationException
Problem
While building the Gift API at Kakao Tech Campus, I implemented a feature to add products to a wishlist. The question was: how should I handle invalid product IDs?
Method 1: Relying on DB Constraints
Catch DataIntegrityViolationException when a foreign key constraint is violated.
1
2
3
4
5
6
7
8
9
10
@Transactional
public WishlistItemDto addItem(Member member, Long productId) {
try {
WishlistItem item = new WishlistItem(member, productId);
wishlistRepository.save(item);
return new WishlistItemDto(item);
} catch (DataIntegrityViolationException e) {
throw new EntityNotFoundException("Product does not exist.");
}
}
Problems:
DataIntegrityViolationExceptioncovers more than just FK violations- The exception scope is too broad—hard to pinpoint the actual cause
- You’re hitting the DB just to find out something failed
Method 2: Validation at Application Level
Check if the product exists before saving.
1
2
3
4
5
6
7
8
9
@Transactional
public WishlistItemDto addItem(Member member, Long productId) {
Product product = productRepository.findById(productId)
.orElseThrow(() -> new EntityNotFoundException("Product does not exist."));
WishlistItem item = new WishlistItem(member, product);
wishlistRepository.save(item);
return new WishlistItemDto(item);
}
Advantages:
- Exceptions are precise
- Avoids unnecessary DB queries
- Business logic is explicit in the code
Mentor Feedback
I asked my mentor which approach was better.
“From the perspective that we shouldn’t blindly trust external (DB-level) validation, application-level validation is the way to go.”
In short:
- DB constraints are the last line of defense
- Validate at the application level first
- Exception messages become more meaningful
Lessons Learned
- Relying solely on DB constraints makes exception handling vague
- Application-level validation leads to clearer code and easier debugging
- I learned the defensive programming principle of “never trust external validation”
From Kakao Tech Campus 3rd cohort Gift API clone coding, summarizing mentor feedback.
This post is licensed under CC BY 4.0 by the author.