Chaeyeon0 / GreenDay_Study

여은개의 공부 일지
0 stars 0 forks source link

[20240526] 히스토리, 레파지토리 패키지 빌드 #31

Open Chaeyeon0 opened 1 month ago

Chaeyeon0 commented 1 month ago

히스토리 패키지 빌드가 되도록 기능 구현은 해놓긴 했습니다 ! -> 그린데이 이슈 브랜치 파서 거기다가 연결도 해 놓았구요 ! 커밋 사항에 대해선 왑 그린데이 이슈 브랜치를 통해서 확인해주셔야할 것 같습니다. 일단 먼저 코드에 대해서 다 보여드리자면

package com.example.greendayhistory.domain.entity;
import jakarta.persistence.*;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedDate;
import java.time.LocalDateTime;
@Entity
@Table(name="history")
@Getter
@NoArgsConstructor
public class Historyentity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)

    @Column(nullable = false)
    private Integer pageId;

    @Column(length = 200)
    private String diaryContent;

    @Column(length = 255)
    private String loginId;

    @CreatedDate // 해당 필드가 생성 날짜를 자동으로 기록하도록 설정 (Spring Data JPA)
    @Column(nullable = false, updatable = false)
    private LocalDateTime createdAt;
    @Builder
    public Historyentity(Integer pageId, String diaryContent, String loginId) {
        this.pageId = pageId;
        this.diaryContent = diaryContent;
        this.loginId = loginId;
    }

}

}


- 여기는 레파지토리
```java
package com.example.greendayhistory.repository;
import com.example.greendayhistory.domain.entity.Historyentity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public interface Historyrepository extends JpaRepository<Historyentity, Integer> {
    Historyentity findByPageId(Integer pageId);
    List<Historyentity> findByLoginIdOrderByCreatedAtAsc(String loginId);
}

-서비스

package com.example.greendayhistory.service;
import com.example.greendayhistory.domain.entity.Historyentity;
import com.example.greendayhistory.dto.HistoryDto;
import com.example.greendayhistory.repository.Historyrepository;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class Historyservice {
    private final Historyrepository historyRepository;

    @Autowired
    public Historyservice(Historyrepository historyRepository) {
        this.historyRepository = historyRepository;
    }

    // 특정 페이지 ID에 해당하는 히스토리를 가져오는 메서드
    public HistoryDto getHistoryByPageId(Integer pageId) {
        Historyentity historyEntity = historyRepository.findByPageId(pageId);
        if (historyEntity == null) {
            throw new EntityNotFoundException("History not found for page id: " + pageId);
        }
        return convertToDto(historyEntity);
    }

    // 로그인된 사용자의 최초 7개의 히스토리 목록을 가져오는 메서드
    public List<HistoryDto> getInitialHistories(String loginId) {
        List<Historyentity> userHistories = historyRepository.findByLoginIdOrderByCreatedAtAsc(loginId);
        if (userHistories.size() < 7) {
            throw new IllegalStateException("Not enough history entries to display.");
        }
        return userHistories.stream()
                .limit(7)
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }

    // 이전 히스토리 목록을 7개씩 그룹화하여 가져오는 메서드
    public List<HistoryDto> getGroupedHistories(String loginId, int groupNumber) {
        List<Historyentity> userHistories = historyRepository.findByLoginIdOrderByCreatedAtAsc(loginId);
        int fromIndex = groupNumber * 7;
        int toIndex = Math.min(fromIndex + 7, userHistories.size());

        if (fromIndex >= userHistories.size()) {
            throw new IllegalStateException("No more history entries to display.");
        }

        return userHistories.subList(fromIndex, toIndex).stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }

    // 엔터티를 DTO로 변환하는 메서드
    private HistoryDto convertToDto(Historyentity entity) {
        return HistoryDto.builder()
                .page_id(entity.getPageId())
                .diary_content(entity.getDiaryContent())
                .login_id(entity.getLoginId())
                .build();
    }
}
package com.example.greendayhistory.controller;
import com.example.greendayhistory.dto.HistoryDto;
import com.example.greendayhistory.service.Historyservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/history")  // 이 컨트롤러의 기본 URL 경로를 "/history"로 설정
public class Historycontroller {
    private final Historyservice historyService;

    // 생성자를 통해 Historyservice를 주입받음
    @Autowired
    public Historycontroller(Historyservice historyService) {
        this.historyService = historyService;
    }

    // 특정 페이지 ID에 해당하는 히스토리를 가져오는 엔드포인트
    @GetMapping("/page/{pageId}")
    public HistoryDto getHistoryByPageId(@PathVariable Integer pageId) {
        // 페이지 ID를 기준으로 히스토리를 조회하여 반환
        return historyService.getHistoryByPageId(pageId);
    }

    // 로그인된 사용자의 최초 7개의 히스토리 목록을 가져오는 엔드포인트
    @GetMapping("/initial")
    public List<HistoryDto> getInitialHistories(@RequestParam String loginId) {
        // 로그인 ID를 기준으로 최초 7개의 히스토리를 조회하여 반환
        return historyService.getInitialHistories(loginId);
    }

    // 이전 히스토리 목록을 7개씩 그룹화하여 가져오는 엔드포인트
    @GetMapping("/group")
    public List<HistoryDto> getGroupedHistories(@RequestParam String loginId, @RequestParam int groupNumber) {
        // 로그인 ID와 그룹 번호를 기준으로 히스토리를 7개씩 그룹화하여 조회하여 반환
        return historyService.getGroupedHistories(loginId, groupNumber);
    }
}
package com.example.greendayhistory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@EnableJpaAuditing
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class GreendayHistoryApplication {

    public static void main(String[] args) {
        SpringApplication.run(GreendayHistoryApplication.class, args);
    }

}

이렇게 완성 ! 근데 수정할 사항이 생겨버렸어요