Skip to content

Commit

Permalink
Feat : CHAT-290-캘린더-조회-API-수정 (#49)
Browse files Browse the repository at this point in the history
* Feat : TypedQuery 작성위해 의존추가

* Feat : TypedQuery 작성위해 의존추가

* Feat : DTO 변경

* Feat : 레포지토리 작성

* Feat : 리펙토링

기존 DiaryList 레포지토리의 쿼리 활용 위해 일반적인 쿼리는 분리후 재사용

* Feat : 서비스계층

추가적인 쿼리 작성없이 일기조회 기능 구현 기본적인 기능 구현

* Feat : 컨트롤러 걔층

반환하는 DTO 변경으로인한 수정 소요

* Fix : 쿼리수정

User가 날짜에있으면 조회가 안되는 버그가있어 쿼리 수정

* Fix : findMostActiveSender 매서드 수정

쿼리를 통해 데이터를 먼저 걸러와서, 불필요한 데이터 조회 안함 + 필요없는 조건문 제거

* Fix : findMostActiveSender 수정

MAX를 이용해 Sender 별로 가장 최근값을 비교해 내림차순해서 정렬하게 함
  • Loading branch information
Mouon authored Feb 14, 2024
1 parent a8d5469 commit a146e2e
Show file tree
Hide file tree
Showing 8 changed files with 92 additions and 139 deletions.
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ repositories {
}

dependencies {

implementation 'org.hibernate:hibernate-core:6.4.2.Final'
implementation 'org.json:json:20220320'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package com.kuit.chatdiary.controller.calendar;

import com.kuit.chatdiary.domain.Sender;
import com.kuit.chatdiary.dto.CalendarInquiryResponse;
import com.kuit.chatdiary.dto.DateInquiryResponse;
import com.kuit.chatdiary.dto.CalendarInquiryResponseDTO;
import com.kuit.chatdiary.service.calendar.CalendarInquiryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
Expand All @@ -12,11 +10,8 @@
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("chat")
Expand All @@ -27,11 +22,11 @@ public CalendarInquiryController(CalendarInquiryService calendarInquiryService)
this.calendarInquiryService = calendarInquiryService;
}
@GetMapping("/chat")
public ResponseEntity<List<DateInquiryResponse>> getChatExistsByMonth(
public ResponseEntity<List<CalendarInquiryResponseDTO>> getChatExistsByMonth(
@RequestParam("memberId") long memberId,
@RequestParam("month") @DateTimeFormat(pattern = "yyyy-MM") YearMonth month) {

List<DateInquiryResponse> chatExistsByMonth = calendarInquiryService.existsChatByMonth(memberId, month);
List<CalendarInquiryResponseDTO> chatExistsByMonth = calendarInquiryService.getCalendarInquiryResponses(memberId,month);
return ResponseEntity.ok(chatExistsByMonth);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@
import com.kuit.chatdiary.domain.Sender;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
public class CalendarInquiryResponse {
@NoArgsConstructor
public class CalendarInquiryResponseDTO {
private String dates;
private Sender sender;
private boolean exists;
}
}
18 changes: 0 additions & 18 deletions src/main/java/com/kuit/chatdiary/dto/DateInquiryResponse.java

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -16,31 +16,39 @@

@Repository
public class DiaryListRepository {
private final EntityManager em;

public DiaryListRepository(EntityManager em) {
private final EntityManager em;
public DiaryListRepository(EntityManager em) {
this.em = em;
}

/** 우선 쿼리 세개 날리기.. */
public List<DiaryListResponseDTO> inquiryDiaryRange(Long userId, Date startDate, Date endDate) {
List<Diary> diaries = em.createQuery("SELECT d FROM diary d WHERE d.member.userId = :userId AND d.diaryDate BETWEEN :startDate AND :endDate", Diary.class)
.setParameter("userId", userId)
.setParameter("startDate", startDate, TemporalType.DATE)
.setParameter("endDate", endDate, TemporalType.DATE)
.getResultList();

return diaries.stream().map(diary -> {
List<DiaryPhoto> diaryPhotos = em.createQuery("SELECT dp FROM diaryphoto dp WHERE dp.diary = :diary", DiaryPhoto.class)
.setParameter("diary", diary)
.getResultList();
List<DiaryTag> diaryTags = em.createQuery("SELECT dt FROM diarytag dt WHERE dt.diary = :diary", DiaryTag.class)
.setParameter("diary", diary)
.getResultList();

return new DiaryListResponseDTO(diary, diaryPhotos, diaryTags);
}).collect(Collectors.toList());
}
/**
* 중복되는 쿼리 따로 분리
* 재사용성 높이기
*/
public List<Diary> getDiaries(Long userId, Date startDate, Date endDate) {
return em.createQuery("SELECT d FROM diary d WHERE d.member.userId = :userId AND d.diaryDate BETWEEN :startDate AND :endDate", Diary.class)
.setParameter("userId", userId)
.setParameter("startDate", startDate, TemporalType.DATE)
.setParameter("endDate", endDate, TemporalType.DATE)
.getResultList();
}

public List<DiaryListResponseDTO> inquiryDiaryRange(Long userId, Date startDate, Date endDate) {
return getDiaries(userId, startDate, endDate).stream()
.map(diary -> {
List<DiaryPhoto> diaryPhotos = em.createQuery("SELECT dp FROM diaryphoto dp WHERE dp.diary = :diary", DiaryPhoto.class)
.setParameter("diary", diary)
.getResultList();
List<DiaryTag> diaryTags = em.createQuery("SELECT dt FROM diarytag dt WHERE dt.diary = :diary", DiaryTag.class)
.setParameter("diary", diary)
.getResultList();

return new DiaryListResponseDTO(diary, diaryPhotos, diaryTags);
}).collect(Collectors.toList());
}


}


Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.kuit.chatdiary.repository.statics;

import com.kuit.chatdiary.domain.Sender;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import org.springframework.stereotype.Repository;

import java.sql.Date;
Expand All @@ -27,4 +29,25 @@ public List<Object[]> countChatsBySenderAndDate(Long userId, Date startDate, Dat
.setParameter("endDate", endDate)
.getResultList();
}

public Sender findMostActiveSender(long userId, Date diaryDate) {
String jpql = "SELECT c.sender FROM chat c " +
"WHERE c.member.id = :memberId AND c.sender != :sender " +
"AND c.createAt >= :startDate AND c.createAt < :endDate " +
"GROUP BY c.sender " +
"ORDER BY COUNT(c) DESC, MAX(c.createAt) DESC";
TypedQuery<Sender> query = em.createQuery(jpql, Sender.class)
.setParameter("memberId", userId)
.setParameter("sender", Sender.USER)
.setParameter("startDate", diaryDate.toLocalDate().atStartOfDay())
.setParameter("endDate", diaryDate.toLocalDate().plusDays(1).atStartOfDay())
.setMaxResults(1);
List<Sender> resultList = query.getResultList();

if (!resultList.isEmpty()) {
return resultList.get(0);
} else {
return null;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,43 +1,50 @@
package com.kuit.chatdiary.service.calendar;

import com.kuit.chatdiary.domain.Diary;
import com.kuit.chatdiary.domain.Sender;
import com.kuit.chatdiary.dto.CalendarInquiryResponse;
import com.kuit.chatdiary.dto.DateInquiryResponse;
import com.kuit.chatdiary.dto.CalendarInquiryResponseDTO;
import com.kuit.chatdiary.repository.diary.DiaryListRepository;
import com.kuit.chatdiary.repository.statics.SenderRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.kuit.chatdiary.repository.CalendarInquiryRepository;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Date;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class CalendarInquiryService {

private final CalendarInquiryRepository calendarInquiryRepository;
private final DiaryListRepository diaryListRepository;
private final SenderRepository senderRepository;

public CalendarInquiryService(CalendarInquiryRepository calendarInquiryRepository) {
this.calendarInquiryRepository = calendarInquiryRepository;
public boolean existsDiary(long memberId, java.util.Date diaryDate) {
List<Diary> diaries = diaryListRepository.getDiaries(memberId, diaryDate, diaryDate);
return !diaries.isEmpty();
}

public List<DateInquiryResponse> existsChatByMonth(long memberId, YearMonth month) {
Map<LocalDate, List<CalendarInquiryResponse>> chatExistsByMonth = calendarInquiryRepository.existsChatByMonth(memberId, month);

List<DateInquiryResponse> list = new ArrayList<>();
/**각 요소들에 대해 반복*/
for(Map.Entry<LocalDate, List<CalendarInquiryResponse>> entry : chatExistsByMonth.entrySet()) {
List<LocalDate> dates = new ArrayList<>();
/**키 값 받아서 리스트에 저장*/
dates.add(entry.getKey());
DateInquiryResponse response = new DateInquiryResponse(dates, entry.getValue());
list.add(response);
}
return list;
}
public List<CalendarInquiryResponseDTO> getCalendarInquiryResponses(long memberId, LocalDate startDate, LocalDate endDate) {
List<CalendarInquiryResponseDTO> responses = new ArrayList<>();

for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
Date diaryDate = Date.valueOf(date);
boolean exists = existsDiary(memberId, diaryDate);
Sender sender = senderRepository.findMostActiveSender(memberId, diaryDate);
responses.add(new CalendarInquiryResponseDTO(diaryDate.toString(), sender, exists));
}

return responses;
}


}
public List<CalendarInquiryResponseDTO> getCalendarInquiryResponses(long memberId, YearMonth month) {
LocalDate startDate = month.atDay(1);
LocalDate endDate = month.atEndOfMonth();
return getCalendarInquiryResponses(memberId, startDate, endDate);
}
}

0 comments on commit a146e2e

Please sign in to comment.