Skip to content

[FIX] 행사 리스트 조회 오류를 수정합니다. - #246

Open
rlajm1203 wants to merge 10 commits into
developfrom
BM/fix/#243/attend-list
Open

[FIX] 행사 리스트 조회 오류를 수정합니다.#246
rlajm1203 wants to merge 10 commits into
developfrom
BM/fix/#243/attend-list

Conversation

@rlajm1203

@rlajm1203 rlajm1203 commented Mar 26, 2025

Copy link
Copy Markdown
Contributor

📌 관련 이슈

closes #243

✒️ 작업 내용

  • 이전에 자신의 Attend 를 기준으로 데이터를 조회하는 방식으로 수정했지만, 제대로 수정이 되지 않아 전통적인 페이지네이션 방식으로 구현했습니다.

스크린샷 🏞️ (선택)

💬 REVIEWER에게 요구사항 💬

Summary by CodeRabbit

  • 신규 기능
    • 특정 날짜 범위 내의 출석 정보를 조회할 수 있는 기능이 추가되었습니다.
  • 리팩토링
    • 기존 자동 페이징 처리 방식에서 전체 데이터를 조회한 후 요청된 페이지와 크기에 맞게 데이터를 수동으로 분할하는 방식으로 개선되었습니다.

@rlajm1203 rlajm1203 added the bug Something isn't working label Mar 26, 2025
@rlajm1203 rlajm1203 self-assigned this Mar 26, 2025
@coderabbitai

coderabbitai Bot commented Mar 26, 2025

Copy link
Copy Markdown

Walkthrough

이 PR은 AttendServicefindMyAttendInfo 메서드 구현을 변경하여 기존의 리포지토리 기반 페이징 대신 전체 데이터를 조회한 후 인덱스를 계산하여 수동으로 페이징하는 방식을 도입합니다. 또한, AttendRepository에 새롭게 findAllByMemberIdAndDateBetween 메서드를 추가하여 지정된 날짜 범위와 삭제 여부 조건에 맞는 데이터를 조회하도록 수정되었습니다.

Changes

File(s) Change Summary
eeos/.../AttendService.java findMyAttendInfo 메서드에서 페이징 처리를 리포지토리 기반에서 전체 리스트 조회 후 수동 인덱스 계산으로 대체함
eeos/.../AttendRepository.java 새 메서드 findAllByMemberIdAndDateBetween 추가: memberId, 시작일, 종료일 및 삭제 상태 조건을 만족하는 AttendEntity 리스트를 반환하도록 구현

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant S as AttendService
    participant R as AttendRepository
    C->>S: findMyAttendInfo(page, size, startDate, endDate) 호출
    S->>R: findAllByMemberIdAndDateBetween(memberId, startDate, endDate) 호출
    R-->>S: 전체 AttendEntity 리스트 반환
    S->>S: 수동 페이징 처리 (인덱스 계산 및 서브리스트 생성)
    S-->>C: PageResponse 반환
Loading

Assessment against linked issues

Objective Addressed Explanation
[FIX] 나의 출석 현황 리스트 조회 시, 행사 대상인 경우만 조회 (#243)

Possibly related PRs

Suggested reviewers

  • Daae-Kim
  • kssumin

Poem

나는 토끼, 코딩 길을 달리며
날짜와 페이지 인덱스를 세며 춤추네
AttendService와 Repository가 손잡고
버그는 멀리, 당근은 가까이
행복한 코드 숲에서 나는 흐뭇히 뛰네 🐰🥕

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copilot AI 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.

Pull Request Overview

This PR fixes the error in fetching the event list by switching from a member‐based pagination query to a more traditional pagination approach using in-memory sublisting. Key changes include:

  • Adding a new repository method (findAllByMemberIdAndDateBetween) to fetch attend records within a date range.
  • Replacing the previous pageable query with manual pagination logic in the service layer.
  • Adjusting the pagination response construction in AttendService.

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
eeos/src/main/java/com/blackcompany/eeos/target/persistence/AttendRepository.java Added a new query method to fetch attend records by member ID and date range.
eeos/src/main/java/com/blackcompany/eeos/target/application/service/AttendService.java Replaced the existing pageable query with logic to retrieve all attend records, then applying manual in-memory pagination.
Comments suppressed due to low confidence (1)

eeos/src/main/java/com/blackcompany/eeos/target/application/service/AttendService.java:251

  • After sublisting, 'myAttend.size()' reflects only the count of items on the current page rather than the full result count, which can mislead pagination. Consider storing the full count in a separate variable before sublisting and using it in the PageImpl constructor.
PageRequest.of(page - 1, size), myAttend.size()

Pageable pageable);

@Query(
"SELECT a FROM AttendEntity a WHERE a.memberId = :memberId AND a.isDeleted = false AND a.createdDate >= :startDate AND a.createdDate <= :endDate")

Copilot AI Mar 26, 2025

Copy link

Choose a reason for hiding this comment

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

The query does not include an ORDER BY clause. Without a consistent order, the results may be paginated inconsistently; consider adding an ORDER BY clause (e.g., 'ORDER BY a.createdDate DESC') for stable pagination.

Suggested change
"SELECT a FROM AttendEntity a WHERE a.memberId = :memberId AND a.isDeleted = false AND a.createdDate >= :startDate AND a.createdDate <= :endDate")
"SELECT a FROM AttendEntity a WHERE a.memberId = :memberId AND a.isDeleted = false AND a.createdDate >= :startDate AND a.createdDate <= :endDate ORDER BY a.createdDate ASC")

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@rlajm1203 벨민님 의견이 궁금합니다~!

@github-actions

github-actions Bot commented Mar 26, 2025

Copy link
Copy Markdown

Test Results

89 tests  ±0   86 ✅ ±0   5s ⏱️ -1s
35 suites ±0    3 💤 ±0 
35 files   ±0    0 ❌ ±0 

Results for commit 1c91e4b. ± Comparison against base commit 20966e5.

♻️ This comment has been updated with latest results.

@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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
eeos/src/main/java/com/blackcompany/eeos/target/application/service/AttendService.java (1)

216-252: 성능 최적화 고려사항!

현재 구현은 두 가지 성능 문제가 있을 수 있습니다:

  1. 전체 데이터를 먼저 조회한 후 메모리에서 페이징 처리하므로, 데이터가 많을 경우 메모리 사용량이 증가할 수 있습니다.

  2. AttendEntity에 대해 별도의 쿼리로 ProgramModel을 조회하고 있어 N+1 쿼리 문제가 발생할 수 있습니다.

최적화 제안:

  1. 이미 총 개수를 알고 있다면, 쿼리 한 번으로 총 개수와 페이지 데이터를 모두 가져오는 것이 좋습니다.

  2. N+1 쿼리 문제를 해결하기 위해 프로그램 ID 목록을 수집하여 한 번에 조회하는 방식을 고려해보세요:

// 페이지 데이터 조회 후
List<Long> programIds = myAttend.stream()
        .map(AttendEntity::getProgramId)
        .distinct()
        .collect(Collectors.toList());

Map<Long, ProgramModel> programMap = programRepository.findAllById(programIds).stream()
        .map(programEntityConverter::from)
        .collect(Collectors.toMap(ProgramModel::getId, program -> program));

// 이후 변환 로직에서 Map을 활용
.map(attendModel -> {
    ProgramModel program = programMap.get(attendModel.getProgramId());
    if (program == null) return null;
    return attendInfoWithProgramConverter.from(attendModel, program);
})
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 20966e5 and 8e86639.

📒 Files selected for processing (2)
  • eeos/src/main/java/com/blackcompany/eeos/target/application/service/AttendService.java (2 hunks)
  • eeos/src/main/java/com/blackcompany/eeos/target/persistence/AttendRepository.java (1 hunks)
🔇 Additional comments (3)
eeos/src/main/java/com/blackcompany/eeos/target/persistence/AttendRepository.java (1)

69-74: 새로운 메서드 추가가 올바르게 이루어졌습니다!

새로 추가된 findAllByMemberIdAndDateBetween 메서드는 기존 findAllByMemberIdAndCreatedDateGreaterThan 메서드와 유사하지만 몇 가지 중요한 차이점이 있습니다:

  1. Page<AttendEntity> 대신 List<AttendEntity>를 반환
  2. 날짜 비교 연산자가 ><(불포함)에서 >=<=(포함)으로 변경
  3. 메서드 이름이 기능을 더 정확하게 반영

이러한 변경은 PR 목표에 맞게 페이징 방식을 변경하기 위한 적절한 개선입니다.

eeos/src/main/java/com/blackcompany/eeos/target/application/service/AttendService.java (2)

216-219: Repository 메서드 호출이 적절하게 수정되었습니다!

페이징 방식 변경에 맞게 findAllByMemberIdAndDateBetween 메서드를 사용하도록 코드가 수정되었습니다. 이 변경으로 인해 데이터베이스 레벨에서의 페이징 대신 애플리케이션 레벨에서 페이징을 처리할 수 있게 되었습니다.


222-233: 수동 페이징 구현이 효과적으로 이루어졌습니다!

애플리케이션 레벨에서의 페이징 처리가 명확하고 논리적으로 구현되었습니다:

  1. 시작 인덱스와 종료 인덱스 계산
  2. 범위를 벗어나는 경우에 대한 예외 처리
  3. 빈 페이지 반환 처리

이 방식은 이전 구현에서 발생했던 행사 리스트 조회 오류를 해결할 것으로 예상됩니다.

Comment on lines +251 to +252
PageRequest.of(page - 1, size),
myAttend.size());

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

총 요소 수 계산 로직 검토 필요!

PageImpl 생성자의 세 번째 매개변수는 전체 요소의 수여야 합니다. 현재 구현에서는 myAttend.size()를 사용하고 있는데, 이 값은 페이징 처리 후의 하위 목록 크기입니다.

이로 인해 애플리케이션의 페이지 탐색에 문제가 발생할 수 있습니다. 전체 데이터 셋의 크기를 전달해야 총 페이지 수가 정확하게 계산됩니다.

다음과 같이 수정하는 것을 제안합니다:

+ int totalSize = attendRepository.findAllByMemberIdAndDateBetween(
+         memberId, new Timestamp(startDate), new Timestamp(endDate)).size();
  responses =
          new PageImpl<>(
                  myAttend.stream()
                          .map(attendEntityConverter::from)
                          .map(
                                  attendModel -> {
                                      ProgramModel program =
                                              programRepository
                                                      .findById(attendModel.getProgramId())
                                                      .map(programEntityConverter::from)
                                                      .orElse(null);
                                      if (program == null) return null;
                                      return attendInfoWithProgramConverter.from(attendModel, program);
                                  })
                          .filter(Objects::nonNull)
                          .toList(),
                  PageRequest.of(page - 1, size),
-                 myAttend.size());
+                 totalSize);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
PageRequest.of(page - 1, size),
myAttend.size());
int totalSize = attendRepository.findAllByMemberIdAndDateBetween(
memberId, new Timestamp(startDate), new Timestamp(endDate)).size();
responses =
new PageImpl<>(
myAttend.stream()
.map(attendEntityConverter::from)
.map(
attendModel -> {
ProgramModel program =
programRepository
.findById(attendModel.getProgramId())
.map(programEntityConverter::from)
.orElse(null);
if (program == null) return null;
return attendInfoWithProgramConverter.from(attendModel, program);
})
.filter(Objects::nonNull)
.toList(),
PageRequest.of(page - 1, size),
totalSize);

- 생성일을 기준으로 내림차순
- 페이징 처리 후 size 가 아닌, 전체 size 로 수정

@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.

Actionable comments posted: 0

🧹 Nitpick comments (1)
eeos/src/main/java/com/blackcompany/eeos/target/application/service/AttendService.java (1)

223-235: 수동 페이지네이션 로직이 적절히 구현되었습니다.

애플리케이션 레벨에서 페이지네이션을 처리하기 위한 로직이 잘 구현되었습니다. 요청된 페이지가 데이터 범위를 벗어나는 경우와 마지막 페이지의 크기 조정을 모두 적절히 처리하고 있습니다.

다만, 대용량 데이터셋의 경우 전체 데이터를 메모리에 로드하는 방식은 성능 이슈가 발생할 수 있습니다. 현재는 행사 리스트 조회 문제 해결을 위한 변경이지만, 장기적으로는 데이터베이스 수준의 페이지네이션을 최적화하는 방안도 고려해보시기 바랍니다.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 71083c4 and 1c91e4b.

📒 Files selected for processing (1)
  • eeos/src/main/java/com/blackcompany/eeos/target/application/service/AttendService.java (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (3)
eeos/src/main/java/com/blackcompany/eeos/target/application/service/AttendService.java (3)

216-218: 데이터 조회 방식이 변경되었습니다.

이전에는 페이지네이션을 리포지토리 레벨에서 처리했지만, 이제는 전체 데이터를 먼저 조회한 후 애플리케이션 레벨에서 페이지네이션을 적용하는 방식으로 변경되었습니다. 이는 PR 목적에 맞게 행사 리스트 조회 오류를 해결하기 위한 변경으로 보입니다.


220-220: 총 요소 수 계산이 올바르게 수정되었습니다.

이전 코드 리뷰에서 지적된 문제를 해결하기 위해 전체 요소 수를 올바르게 계산하고 있습니다. 페이징 처리 전의 전체 데이터 크기를 totalSize에 저장하고 있어 올바른 페이지 정보가 제공됩니다.


253-254: PageImpl 생성자 매개변수가 올바르게 수정되었습니다.

이전 리뷰에서 지적된 PageImpl 생성자의 세 번째 매개변수 문제가 수정되었습니다. 이제 페이징 처리 전의 전체 데이터 크기인 totalSize를 전달하여 총 페이지 수가 정확하게 계산됩니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FIX] 나의 출석 현황 리스트 조회 오류를 해결합니다.

3 participants