Skip to content

[FEAT] 채팅방 목록 최신 채팅순 정렬#1351

Merged
jye326 merged 3 commits intodevelopfrom
feature/1350-order-chat-room-previews
Mar 9, 2026
Merged

[FEAT] 채팅방 목록 최신 채팅순 정렬#1351
jye326 merged 3 commits intodevelopfrom
feature/1350-order-chat-room-previews

Conversation

@jye326
Copy link
Contributor

@jye326 jye326 commented Feb 25, 2026

Issue Number

closed #1350

As-Is

채팅방 목록이 정렬 기준이 없었습니다.

To-Be

애플리케이션 단 정렬 기준을 추가했습니다.

  1. 마지막 채팅 메시지의 생성시간(최신순)
  2. 아직 채팅을 하지 않은 채팅방의 경우는 채팅방 생성 시간(최신순)

채팅방 미리보기 기능 관련 인덱스를 추가했습니다.

  1. 채팅방을 findAllByMenteeIdOrMentorId 로 진행하고 있었기에 chat_roommenteeId, mentorId 인덱스를 각각 추가
  2. 채팅방 별 마지막 메시지를 SELECT MAX(id) FROM chat_message WHERE chat_room_id IN (...) GROUP BY chat_room_id 로 조회하고 있었기에 chat_messagechat_room_id 인덱스 추가

Check List

  • 테스트가 전부 통과되었나요?
  • 모든 commit이 push 되었나요?
  • merge할 branch를 확인했나요?
  • Assignee를 지정했나요?
  • Label을 지정했나요?
  • 닫을 이슈 번호를 지정했나요?

Summary by CodeRabbit

업데이트 사항

  • 기능 개선
    • 채팅방 목록이 최신 메시지 기준으로 자동 정렬되어 표시됩니다.
    • 채팅 기능의 성능이 최적화되었습니다.

- 채팅방 리스트를 최근 메시지 또는 생성일 기준으로 정렬하는 로직 추가
- `ChatRoom`의 생성일 필드(`createdAt`)에 Getter 추가
- `chat_room`: 멘티, 멘토별 채팅방 목록 조회 인덱스 추가 (`mentee_id`, `mentor_id`)
- `chat_message`: 채팅방별 마지막 메시지 조회 인덱스 추가 (`chat_room_id`)
@jye326 jye326 requested review from dye0p and kimdevv February 25, 2026 08:59
@jye326 jye326 self-assigned this Feb 25, 2026
@jye326 jye326 added ✨ BE 백엔드 ☘️ feat 기능 구현 labels Feb 25, 2026
@jye326 jye326 linked an issue Feb 25, 2026 that may be closed by this pull request
@coderabbitai
Copy link

coderabbitai bot commented Feb 25, 2026

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5169d278-dea3-4537-9e45-dc021735f4c4

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

채팅방 목록을 최신 메시지 시간순으로 정렬하는 기능이 추가되었습니다. ChatRoomFacadeServiceComparator를 활용한 정렬 로직이 구현되었고, ChatRoomcreatedAt 필드에 @Getter 애너테이션이 추가되어 조회 가능하게 했습니다. 마지막으로 chat_roomchat_message 테이블에 조회 성능을 개선하기 위한 인덱스가 마이그레이션을 통해 추가되었습니다.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

코치의 한마디 ✨

정렬 기능을 추깝게 추가했네요! 몇 가지 챙겨보면 더 좋을 것 같습니다.

1. Null 안전성
getComparing() 메서드에서 lastMessageByRoomId.get(room.getId())가 null을 반환할 수 있는데, NPE 방지 코드가 필요합니다. Objects.nonNull()이나 Optional을 활용한 defensive coding이 권장됩니다. (Java Null Safety Best Practices)

2. 인덱스 순서 검토
DB 마이그레이션에서 idx_mentee_id on (mentee_id, id DESC)는 좋지만, 실제 쿼리 패턴을 다시 확인해보세요. createdAt 컬럼 기반 정렬이 더 빈번하다면 인덱스 전략을 조정할 여지가 있습니다.

3. 문서화
getComparing() 메서드에 간단한 JavaDoc을 추가하면 의도가 더 명확해집니다. ("마지막 메시지 기준으로 정렬하는 Comparator 반환...")

성능까지 함께 고려한 좋은 변경입니다! 💪

📋 밤새 채팅 다시 읽으면
최신 순으로 정렬되니
마음도 한결 가벼워진다
인덱스까지 챙겨주니
데이터베이스도 호들갑! 🚀

🚥 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
Title check ✅ Passed PR 제목이 변경사항의 핵심을 명확히 반영하고 있으며, 채팅방 목록을 최신 채팅순으로 정렬하는 주요 기능을 정확하게 설명합니다.
Description check ✅ Passed PR 설명이 템플릿의 모든 필수 섹션을 포함하고 있으며, As-Is/To-Be, 체크리스트가 완벽히 작성되어 있습니다.
Linked Issues check ✅ Passed PR의 코드 변경사항이 #1350 이슈의 목표인 '마지막 채팅 시간순 정렬' 요구사항을 모두 충족하고 있습니다.
Out of Scope Changes check ✅ Passed 모든 변경사항이 채팅방 정렬 기능 및 성능 최적화와 직접 관련되어 있으며, 범위를 벗어난 변경은 없습니다.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/1350-order-chat-room-previews

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


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

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1ffd722a4f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +87 to +91
return Comparator.comparing(
room -> {
ChatMessage lastMessage = lastMessageByRoomId.get(room.getId());
if (lastMessage == null) {
return room.getCreatedAt();

Choose a reason for hiding this comment

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

P2 Badge Add tie-breaker when sorting chat room previews

The new comparator orders rooms only by createdAt (last message time or room creation time), but chat_room.created_at/chat_message.created_at are defined as DATETIME without sub-second precision in existing migrations, so multiple rooms frequently share the same sort key; in that case Stream.sorted falls back to the repository encounter order, and findAllByMenteeIdOrMentorId has no ORDER BY, which can produce unstable ordering across requests and place effectively newer activity behind older rooms when events occur in the same second. Adding a deterministic secondary key (e.g., last message id or room id descending) would avoid this.

Useful? React with 👍 / 👎.

@dye0p
Copy link
Contributor

dye0p commented Feb 26, 2026

@CodeRabbit 리뷰해줘

@coderabbitai
Copy link

coderabbitai bot commented Feb 26, 2026

@dye0p, 채팅방 목록 정렬 기능 추가 PR을 검토하겠습니다! 최신 채팅순 정렬과 인덱스 추가 내용을 꼼꼼히 살펴보겠습니다. 🐰

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@backend/fittoring/src/main/java/fittoring/application/chat/service/ChatRoomFacadeService.java`:
- Line 21: The file ChatRoomFacadeService.java contains an unused import
"lombok.NonNull"; remove that import from the top of the file (or run your IDE's
"Optimize Imports"/organize imports) so the class no longer references an unused
symbol and imports are clean.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4b4bb64 and 1ffd722.

📒 Files selected for processing (3)
  • backend/fittoring/src/main/java/fittoring/application/chat/service/ChatRoomFacadeService.java
  • backend/fittoring/src/main/java/fittoring/domain/model/ChatRoom.java
  • backend/fittoring/src/main/resources/db/migration/V202602251700__add_indexes_to_chat_tables.sql

import java.util.List;
import java.util.Map;
import java.util.Optional;
import lombok.NonNull;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

사용되지 않는 import를 제거해주세요.

lombok.NonNull이 import되어 있지만 코드에서 사용되지 않습니다. IDE의 "Optimize Imports" 기능을 활용하면 쉽게 정리할 수 있습니다.

🧹 제거 제안
 import java.util.Comparator;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
-import lombok.NonNull;
 import lombok.RequiredArgsConstructor;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@backend/fittoring/src/main/java/fittoring/application/chat/service/ChatRoomFacadeService.java`
at line 21, The file ChatRoomFacadeService.java contains an unused import
"lombok.NonNull"; remove that import from the top of the file (or run your IDE's
"Optimize Imports"/organize imports) so the class no longer references an unused
symbol and imports are clean.

Copy link
Contributor

@dye0p dye0p left a comment

Choose a reason for hiding this comment

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

UI와 관련된 코멘트 하나 있는데 확인해주시면 좋을 것 같아요~ 그 외엔 별다른 코멘트가 없어 승인합니다!

- 메시지가 없는 채팅방 미리보기 목록 제외 필터 추가
- 테스트 데이터 개선: 메시지가 없는 채팅방 미리보기 목록 제외 시나리오 추가
- RestDocs 문서화 수정: 선택적 필드 옵션 제거 및 설명 수정
@jye326 jye326 merged commit bf25755 into develop Mar 9, 2026
2 checks passed
@jye326 jye326 deleted the feature/1350-order-chat-room-previews branch March 9, 2026 09:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

✨ BE 백엔드 ☘️ feat 기능 구현

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

[FEAT] 채팅방 목록 최신 채팅순 정렬

2 participants