타임라인 API 설계

    기능 Method URL Return
    메모 생성 POST /api/memos Memo
    메모 조회 GET /api/memos List<Memo>
    메모 변경 PUT /api/memos/{id} Long
    메모 삭제 DELETE /api/memos/{id} Long

     

    프로젝트 생성

    ➡️ 메모는 1) 익명의 작성자 이름(username), 2) 메모 내용(contents)로 구성 

    • domain (src > main > java > com.sparta.week03 에 패키지 생성)
      • Memo.java
        @NoArgsConstructor	// 기본 생성자 생성
        @Getter
        @Entity	// 테이블과 연계됨을 스프링에게 알림
        public class Memo extends Timestamped {
            @GeneratedValue(strategy = GenerationType.AUTO)
            @Id
            private Long id;
        
            @Column(nullable = false)
            private String username;
        
            @Column(nullable = false)
            private String contents;
            
            public Memo(String username, String contents) {
            	this.username = username;
                this.contents = contents;
            }
            
            public Memo(MemoRequestDto requestDto) {
                this.username = requestDto.getUsername();
                this.contents = requestDto.getContents();
            }
        
            public void update(MemoRequestDto requestDto) {
                this.username = requestDto.getUsername();
                this.contents = requestDto.getContents();
            }
        }
      • Timestamped.java
        @Getter	// 데이터 연결을 위해
        @MappedSuperclass	// Entitiy가 자동으로 컬럼으로 인식
        @EntityListeners(AuditingEntityListener.class)	// 생성/변경 시간을 자동으로 업데이트
        public class Timestamped {
        
            @CreatedDate
            private LocalDateTime createAt;
        
            @LastModifiedDate
            private LocalDateTime modifiedAt;
        }
      • MemoRequestDto.java
        @Getter
        public class MemoRequestDto {
            private String username;
            private String contents;
        }
      • MemoRepository.java - Interface / ID가 Long 타입
        public interface MemoRepository extends JpaRepository<Memo, Long> {
            List<Memo> findAllByOrderByModifiedAtDesc();
        }
    • service (src > main > java > com.sparta.week03 에 패키지 생성)
      • MemoService.java
        @RequiredArgsConstructor
        @Service
        public class MemoService {
            private final MemoRepository memoRepository;
        
            @Transactional
            public Long update(Long id, MemoRequestDto requestDto) {
                Memo memo = memoRepository.findById(id).orElseThrow(
                        () -> new IllegalArgumentException("아이디가 존재하지 않습니다.")
                );
                memo.update(requestDto);
                return memo.getId();
            }
        }
    • controller (src > main > java > com.sparta.week03 에 패키지 생성)
      • MemoController.java
        @RequiredArgsConstructor
        @RestController
        public class MemoController {
        
            private final MemoRepository memoRepository;
            private final MemoService memoService;
        
            @PostMapping("/api/memos")
            public Memo createMemo(@RequestBody MemoRequestDto requestDto) {
                Memo memo = new Memo(requestDto);
                return memoRepository.save(memo);
            }
        
            @GetMapping("/api/memos")
            public List<Memo> getMemos() {
                return memoRepository.findAllByOrderByModifiedAtDesc();
            }
        
            @PutMapping("/api/memos/{id}")
            public Long updateMemo(@PathVariable Long id, @RequestBody MemoRequestDto requestDto) {
                memoService.update(id, requestDto);
                return id;
            }
        
            @DeleteMapping("/api/memos/{id}")
            public Long deleteMemo(@PathVariable Long id) {
                memoRepository.deleteById(id);
                return id;
            }
        }
    • Spring에게 Auditing 기능을 사용하고 있다고 알려주어야 함
      ➡️ Week03Application.java@EnableJpaAuditing 추가

     

    Spring jpa localtime between

    - 메모 목록의 시간을 조회시간으로부터 24시간 이내로 변경

    - 지금: LocalDateTime.now(), 하루 전: LocalDateTime.now().minusDays(1)

    • MemoRepository.java
      public interface MemoRepository extends JpaRepository<Memo, Long> {
          List<Memo> findAllByModifiedAtBetweenOrderByModifiedAtDesc(LocalDateTime start, LocalDateTime end);
      }

     

    • MemoController.java
      // 중략 //
      
      @GetMapping("/api/memos")
      public List<Memo> getMemos() {
          LocalDateTime start = LocalDateTime.now().minusDays(1);
          LocalDateTime end = LocalDateTime.now();
          return memoRepository.findAllByModifiedAtBetweenOrderByModifiedAtDesc(start, end);
      }
      
      // 중략 //

    + Recent posts