Skip to content

[FIX] 품목 수정시 품목코드 에러 수정#44

Merged
yangjiseonn merged 1 commit into
mainfrom
SPM-459
Nov 7, 2025
Merged

[FIX] 품목 수정시 품목코드 에러 수정#44
yangjiseonn merged 1 commit into
mainfrom
SPM-459

Conversation

@yangjiseonn
Copy link
Copy Markdown
Contributor

@yangjiseonn yangjiseonn commented Nov 7, 2025

📝 Summary

  • 품목 수정 시 품목코드 에러 수정

🙏 Question & PR point

📬 Reference

Summary by CodeRabbit

릴리스 노트

  • 버그 수정
    • 부품 코드 생성 로직을 개선하여 그룹 내 모든 부품을 검사하고 최대 시퀀스 번호를 기반으로 다음 코드를 계산합니다. 이제 부품 코드가 더욱 안정적으로 생성되며 중복을 방지합니다.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 7, 2025

Walkthrough

부품 코드 생성 로직이 최신 항목 기반에서 대상 그룹의 모든 부품을 스캔하여 최대 시퀀스 번호를 찾는 방식으로 변경되었습니다. 새로운 코드는 최대 시퀀스에 1을 더하여 계산되며, 나머지 흐름은 변경되지 않았습니다.

Changes

응집된 파일 및 변경 사항 설명
부품 코드 생성 로직 개선
src/main/java/com/sampoom/backend/api/part/service/PartService.java
단일 최신 항목 기반 코드 생성 방식을 모든 부품 스캔 기반으로 변경. 대상 그룹 내 최대 시퀀스 번호 추출 후 +1로 새 코드 생성. 로깅 추가 및 주석 업데이트.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • 세부 검토 사항:
    • 최대 시퀀스 계산 로직의 정확성 확인
    • 코드 생성 시 예외 케이스 처리 (빈 그룹, 숫자 추출 실패 등)
    • 성능 영향 평가 (모든 부품 스캔으로 인한 데이터베이스 쿼리 부하)
    • 로깅 레벨 및 메시지 적절성 검토

Suggested reviewers

  • Sangyoon98
  • Lee-Jong-Jin
  • CHOOSLA
  • vivivim

Poem

🐰 모든 부품을 세는 토끼의 마법,
최댓값을 찾아 하나를 더하고,
코드는 더욱 견고해졌네요!
순서대로 정렬된 숫자들 속에서,
다음 번호를 찾는 여정 완벽하네! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description check ❓ Inconclusive PR 설명이 템플릿의 필수 섹션은 포함하고 있으나, 요약 내용이 매우 간단하고 관련 이슈 번호(Related Issue)가 누락되어 있습니다. 관련 이슈 번호(close # 형식)를 추가하고, 변경사항에 대한 더 자세한 설명(왜 문제가 있었는지, 어떻게 해결했는지)을 Summary 섹션에 작성해 주세요.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed PR 제목이 주요 변경사항을 명확하게 요약하고 있습니다. 품목 수정 시 품목코드 에러 수정이라는 변경의 핵심을 정확히 전달합니다.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch SPM-459

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.

Copy link
Copy Markdown
Contributor

@taemin3 taemin3 left a comment

Choose a reason for hiding this comment

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

확인했습니다

@yangjiseonn yangjiseonn merged commit 761259c into main Nov 7, 2025
6 of 7 checks passed
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 467bc35 and b3993c2.

📒 Files selected for processing (1)
  • src/main/java/com/sampoom/backend/api/part/service/PartService.java (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (java-kotlin)

Comment on lines +369 to +389
Page<Part> parts = partRepository.findByPartGroupId(groupId, PageRequest.of(0, Integer.MAX_VALUE));

int maxSeq = 0;
for (Part part : parts.getContent()) {
if (part.getCode() != null && part.getCode().startsWith(codePrefix)) {
String[] codeParts = part.getCode().split("-");
if (codeParts.length == 3) {
try {
int seq = Integer.parseInt(codeParts[2]);
maxSeq = Math.max(maxSeq, seq);
} catch (NumberFormatException ignored) {
// 잘못된 형식의 코드는 무시
}
}
}
}

return String.format("%s-%s-%03d", categoryCode, groupCode, nextSeq);
int nextSeq = maxSeq + 1;
String newCode = String.format("%s-%s-%03d", categoryCode, groupCode, nextSeq);

log.debug("그룹 {} 코드 생성: 현재 최대 시퀀스={}, 새 코드={}", groupId, maxSeq, newCode);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Integer.MAX_VALUE 페이지 요청이 런타임 예외를 유발합니다

PageRequest.of(0, Integer.MAX_VALUE)로 모든 부품을 로딩하면 Hibernate 5.3+에서 내부적으로 페이지 크기에 +1을 더해 slice 여부를 판단하는 과정에서 int 오버플로가 발생해 IllegalArgumentException: first-result value cannot be negative가 즉시 던져집니다. 실제로 동일한 패턴을 사용한 코드가 운영 중에 바로 해당 예외로 실패한 사례가 있습니다.(stackoverflow.com) 또한 전체 파트를 한 번에 적재하게 되므로, Spring Data가 기본으로 최대 페이지 크기를 2 000으로 제한하는 이유와 같이 대용량 데이터를 한 번에 읽지 말아야 한다는 가이드라인도 위배됩니다.(jackzhang.cn) 이 로직은 결국 코드 재생성 시 500 에러를 유발할 수 있으므로 반드시 수정이 필요합니다.

권장 수정 방향은 DB가 최댓값을 계산하도록 위임하는 것입니다. 예를 들어 PartRepositoryOptional<String> findFirstByPartGroupIdAndCodeStartingWithOrderByCodeDesc(Long groupId, String prefix); 같은 메서드를 추가해 단 1건만 조회한 뒤, 해당 코드의 시퀀스 부분만 파싱해서 nextSeq를 계산하면 됩니다. 또는 JPQL/SQL로 MAX를 직접 조회해 int로 받아오는 전용 쿼리를 두는 것도 가능합니다. 핵심은 전 테이블 스캔과 Integer.MAX_VALUE 페이징을 제거해 예외와 성능 문제를 동시에 해소하는 것입니다.

🤖 Prompt for AI Agents
In src/main/java/com/sampoom/backend/api/part/service/PartService.java around
lines 369 to 389, the current PageRequest.of(0, Integer.MAX_VALUE) causes int
overflow and loads all parts; replace this approach by delegating the
max-sequence lookup to the database: add a repository method that returns either
the single highest code row (e.g.
findFirstByPartGroupIdAndCodeStartingWithOrderByCodeDesc) or a query that
selects MAX(seq) directly, call that method to obtain the latest code (or max
sequence), parse its sequence part to compute nextSeq, and remove the large page
request and full-table scan to prevent the overflow and performance issue.

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.

2 participants