TIL

73일차 - == 와 === 의 차이점, Spring

haedal-uni 2021. 11. 24. 21:34
728x90

Spring01 _ index.html

 

1. == === 의 차이점 

// 2. 작성한 메모가 올바른지 isValidContents 함수를 통해 확인합니다.
            if (isValidContents(contents) == false) {
                return;
            }

 

이 부분에서 줄이 쳐져 있어서 왜 줄이 쳐져있을까 하고 봤더니 

===으로 바꾸는 것은 어떠냐는 💡가 켜져있었다.

 

 

 

 

 

==와 ===의 차이점은 ==는 Equal Operator이고,  ===는 Strict Equal Operator이다.

 

예시로 보면 ===은 자료형까지 보는 것 같다.

 

console.log(0 == "0"); //true
console.log(0 == "0"); //false

console.log(0 == ""); //true
console.log(0 === ""); //false

 

console.log(null == undefined); // true
console.log(null === undefined) // false

 

 

 

출처 : cheonmr, <[JS Operator] ==와 ===의 차이점>, https://steemit.com/kr-dev/@cheonmr/js-operator

 

 


 

function getMessages() {
            // 1. 기존 메모 내용을 지웁니다.
            $('#cards-box').empty();
            // 2. 메모 목록을 불러와서 HTML로 붙입니다.
            $.ajax({
                type: 'GET',
                url: '/api/memos',
                success: function (response) {
                    for (let i = 0; i < response.length; i++) {
                        let message = response[i];
                        let id = message['id'];
                        let username = message['username'];
                        let contents = message['contents'];
                        let modifiedAt = message['modifiedAt'];
                        addHTML(id, username, contents, modifiedAt);
                    }
                }
            })
        }

 

response로 응답을 받아서 id 등 변수를 지정한다.

 

 

 

 @GetMapping("/api/memos")
    public List<Memo> getMemos() {
        //LocalDateTime start = LocalDateTime.now().minusDays(1); //1시간
        LocalDateTime start = LocalDateTime.now().minusMinutes(1); //1분
        LocalDateTime end = LocalDateTime.now();
        return memoRepository.findAllByModifiedAtBetweenOrderByModifiedAtDesc(start, end);
        //return memoRepository.findAllByOrderByModifiedAtDesc();
    }

 

return값에 시간 제한만 있는데 어떻게 response로 db를 받을까?

 

 

 

memoRepository에 가보면 코드에 List<Memo>라고 적혀있는 것을 볼 수 있다.

 

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

 

findAllByModifiedAtBetweenOrderByModifiedAtDesc가 실행되면 List<Memo>를 가져온다.

jpa Repository에서 이렇게 구현이 되어있다.

 

 

 

아래 create도 마찬가지이다.

JpaRepository를 상속 받으면 자동으로 알아서 데이터 베이스에 저장해 둔다.

   //Create
    @PostMapping("/api/memos")
    public Memo createMemo(@RequestBody MemoRequestDto requestDto) {
        Memo memo = new Memo(requestDto);
        return memoRepository.save(memo);
    }

 


저장되는 커리문은 로그로 insert log에 뜰 것이다.

 

 


2. Spring 02 _ 네이버 쇼핑 api

 

https://developers.naver.com/docs/search/shopping/

 

 

해당 상품 띄우기

query=____

 

 

 

옵션

상품 5개만 띄우기

display = 5

 

 

 

 

 

검색 시작위치

start=2

시작위치를 2로 지정했더니 이 전에 출력되었던 2번째 상품이 먼저 출력되었다.

 

 

 

 

정렬하기

날짜순으로 정렬되어 출력된다.

 

 


 

네이버 쇼핑 api 코드가 어려워서 흐름만 잡기로 했다.

 

그러다가 네이버 쇼핑 api 코드 작성 전 작성했던 sping01과 비교하다가 다른점을 발견했고

이에 문제점을 발견했다.

 

이 전에 작성한 Spring01에서는 create를 Controller에 .save() 했다.

그런데 Controller에서는 save를 하는게 아니라 mapping하는 얘다.

그러므로 아래 Spring01은 잘못된 코드이다.   👉🏻 .save()는 Service에서 하는 것이 맞는 것이다.

 

public class LectureController {
    private final LectureRepository lectureRepository;
    private final LectureService lectureService; // Put은 Service단에서 갖고오므로

    @GetMapping("/api/lectures")
    public List<Lecture> getLectures() {
        return lectureRepository.findAll();
    }

    @PostMapping("/api/lectures")
    public Lecture createLecture(@RequestBody LectureRequestDto requestDto) {
        // requestDto 는, 생성 요청

        Lecture lecture = new Lecture(requestDto);
        // 저장하는 것은 Dto가 아니라 Lecture이니, Dto의 정보를 lecture에 담아야 합니다.
        return lectureRepository.save(lecture);
    }

    @PutMapping("/api/lectures/{id}")
    public Long updateLecture(@PathVariable Long id, @RequestBody LectureRequestDto requestDto) {
        return lectureService.update(id, requestDto);
    }
}

 

 


 

흐름 잡기

 

 

 

update는 reposititory로 가지 않는 이유가 update는 자체적으로 save를 하는 더티체킹을 한다.

 

 

 

JPA 더티 체킹(Dirty Checking)이란?

>> RyanGomdoriPooh, ,  https://interconnection.tistory.com/121

 

 

 

ProductService.java&amp;amp;nbsp;
Product.java

 

 

더티 체킹은 Transaction 안에서 엔티티의 변경이 일어나면,

변경 내용을 자동으로 데이터베이스에 반영하는 JPA 특징이다.

 

데이터베이스에 변경 데이터를 저장하는 시점 :

1) Transaction commit 시점

2) EntityManager flush 시점

3) JPQL 사용 시점

 


update는 @Transactional을 통해서 자체적으로 바꾸는데 .save()는 upsert이다.(update+insert)

그래서 update는 save를 작성하지 않는 것이다.

 

 

 

728x90

'TIL' 카테고리의 다른 글

75일차(.gitignore)  (0) 2021.11.26
74일차(퀴즈 내주기)  (0) 2021.11.25
72일차 _ Spring-1 페어프로그래밍  (0) 2021.11.24
71일차  (0) 2021.11.23
68일차(튜터님께 질문하기)  (0) 2021.11.20