Skip to content

fix: meal retry 시 SQLIntegrityConstraintViolationException 해결 - #677

Merged
1210thatman merged 14 commits into
developfrom
fix/meal-retry-duplicate-entry-flush
Jun 22, 2026
Merged

1210thatman merged 14 commits into
developfrom
fix/meal-retry-duplicate-entry-flush

Conversation

@1210thatman

@1210thatman 1210thatman commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

문제

meal retry API 호출 시 아래 에러로 500 응답 발생:

java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '2026-07-01-BREAKFAST' for key 'tbl_meal.uk_meal_date_type'

원인

JPA Hibernate의 write-behind(지연 쓰기) 동작으로 인해, deleteByYearMonth() 호출 후 DELETE SQL이 DB에 즉시 반영되지 않은 상태에서 INSERT가 시도되어 unique constraint(uk_meal_date_type) 위반 발생.

해결

deleteAllByMealDateBetween() 실행 직후 mealRepository.flush()를 추가하여 DELETE SQL을 DB에 강제 즉시 반영 → 이후 INSERT 진행 시 충돌 없음.

변경 파일

  • MealPersistenceAdapter.kt — deleteByYearMonth() 내 flush() 1줄 추가

🤖 Generated with Claude Code

Summary by CodeRabbit

릴리스 노트

  • 버그 수정
    • 식사 삭제 시 데이터베이스에 즉시 반영되도록 개선했습니다.

ByunDohwi and others added 14 commits December 28, 2025 16:58
deleteByYearMonth 후 flush() 추가하여 JPA write-behind로 인한
DELETE 지연 문제 해결 — INSERT 전에 DELETE가 DB에 반영되도록 보장

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 22, 2026 •

Copy link
Copy Markdown

Walkthrough

MealPersistenceAdapter의 deleteByYearMonth 메서드에서 mealRepository.deleteAllByMealDateBetween(...) 호출 직후 mealRepository.flush()를 추가하여, 삭제 쿼리가 즉시 플러시되도록 동작을 변경했습니다.

Changes

삭제 후 즉시 플러시

Layer / File(s) Summary
deleteByYearMonth 즉시 플러시 추가
src/main/kotlin/dsm/pick2024/domain/meal/persistence/MealPersistenceAdapter.kt
삭제 후 mealRepository.flush() 호출을 추가하여 트랜잭션 종료 전에 삭제 쿼리가 DB에 즉시 반영되도록 변경.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~2 minutes

Poem

🐰 토끼가 당근을 먹고 나서,
바로바로 정리해야 한다냥~
flush() 한 줄로 깔끔하게,
삭제도 즉시 반영되었네!
세상이 이렇게 단순하면 좋겠다 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed PR 제목이 변경의 주요 목적(SQLIntegrityConstraintViolationException 해결)을 정확하게 설명하며, 수정 사항의 핵심을 명확하게 전달합니다.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/meal-retry-duplicate-entry-flush

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
src/main/kotlin/dsm/pick2024/domain/meal/persistence/MealPersistenceAdapter.kt (2)

31-37: 🧹 Nitpick | 🔵 Trivial | 💤 Low value

성능 영향을 고려하세요.

flush() 호출은 DELETE 작업을 즉시 실행하므로 JPA의 배치 최적화가 비활성화됩니다. 현재 사용 사례(단일 월 범위 삭제 후 새 데이터 삽입)에서는 이것이 적절하지만, 대량 데이터 처리나 빈번한 호출 시나리오에서는 성능 병목이 될 수 있습니다.

필요시 다음을 고려하세요:

  • 배치 크기 및 실행 빈도 모니터링
  • 삭제 범위가 큰 경우 청크 단위 처리
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/main/kotlin/dsm/pick2024/domain/meal/persistence/MealPersistenceAdapter.kt`
around lines 31 - 37, The `flush()` call in the `deleteByYearMonth` method
immediately executes the DELETE operation, which disables JPA batch
optimizations and could cause performance issues with large-scale or frequent
deletions. Evaluate whether the immediate flush is necessary for your use case;
if it is, consider adding comments documenting the performance tradeoff and
implement batch processing logic to delete records in chunks when the deletion
range is large (for example, by breaking down the month's date range into
smaller date windows and calling deleteAllByMealDateBetween multiple times in a
loop). Additionally, add monitoring or logging to track the performance
characteristics of this operation.

31-37: 🧹 Nitpick | 🔵 Trivial | ⚖️ Poor tradeoff

향후 고려사항: UPSERT 패턴 검토

현재 "삭제 후 삽입" 패턴은 flush()를 통해 올바르게 작동하지만, 아키텍처 관점에서 MERGE 또는 UPSERT 로직(예: ON DUPLICATE KEY UPDATE 또는 JPA의 merge())을 사용하면 삭제 단계를 제거하고 원자적 작업으로 처리할 수 있습니다.

이는 다음과 같은 이점을 제공합니다:

  • 더 나은 동시성 처리
  • 향상된 성능 (단일 작업)
  • flush 타이밍에 대한 의존성 제거
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/main/kotlin/dsm/pick2024/domain/meal/persistence/MealPersistenceAdapter.kt`
around lines 31 - 37, The deleteByYearMonth method in MealPersistenceAdapter
currently uses a delete-then-flush pattern which is not atomic. Replace this
approach with an UPSERT or MERGE pattern that handles the meal updates as a
single atomic operation. Instead of calling deleteAllByMealDateBetween followed
by flush(), implement a method in the mealRepository that performs an UPSERT
operation (such as JPA's merge() or a custom query using ON DUPLICATE KEY
UPDATE) for the given yearMonth range, eliminating the need for the separate
deletion step and flush call.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@src/main/kotlin/dsm/pick2024/domain/meal/persistence/MealPersistenceAdapter.kt`:
- Around line 31-37: The `flush()` call in the `deleteByYearMonth` method
immediately executes the DELETE operation, which disables JPA batch
optimizations and could cause performance issues with large-scale or frequent
deletions. Evaluate whether the immediate flush is necessary for your use case;
if it is, consider adding comments documenting the performance tradeoff and
implement batch processing logic to delete records in chunks when the deletion
range is large (for example, by breaking down the month's date range into
smaller date windows and calling deleteAllByMealDateBetween multiple times in a
loop). Additionally, add monitoring or logging to track the performance
characteristics of this operation.
- Around line 31-37: The deleteByYearMonth method in MealPersistenceAdapter
currently uses a delete-then-flush pattern which is not atomic. Replace this
approach with an UPSERT or MERGE pattern that handles the meal updates as a
single atomic operation. Instead of calling deleteAllByMealDateBetween followed
by flush(), implement a method in the mealRepository that performs an UPSERT
operation (such as JPA's merge() or a custom query using ON DUPLICATE KEY
UPDATE) for the given yearMonth range, eliminating the need for the separate
deletion step and flush call.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ad328c96-88e7-461f-9f93-2d13f2dc994c

📥 Commits

Reviewing files that changed from the base of the PR and between 35876ce and 0abe32c.

📒 Files selected for processing (1)
  • src/main/kotlin/dsm/pick2024/domain/meal/persistence/MealPersistenceAdapter.kt

@1210thatman
1210thatman merged commit 98d175e into develop Jun 22, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants