inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[개념은 호옹~, 실습 빡] 스프링 부트, 입문!

19 HTTP와 RestController(REST API, 어떻게 만들죠?)

19강 Talend API POST 500 에러

1123

ekdnlt098

작성한 질문수 1

1

안녕하세요. 강의듣던중 오류가 생겨서 코드 남깁니다.

인텔리제이에 코딩한건 아래와 같고,

package com.example.firstproject.api;

import com.example.firstproject.dto.ArticleForm;
import com.example.firstproject.entity.Article;
import com.example.firstproject.repository.ArticleRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController //RestAPI용 컨트롤러. 데이터(JSON)을 반환
public class ArticleApiController {

    @Autowired //DI
    private ArticleRepository articleRepository;

    //GET
    @GetMapping("/api/articles")
    public List<Article> index() {
        return articleRepository.findAll();
    }

    @GetMapping("/api/articles/{id}")
    public Article show(@PathVariable Long id) {
        return articleRepository.findById(id).orElse(null);
    }

    //POST
    @PostMapping("/api/articles")
    public Article create(@RequestBody ArticleForm dto) {
        Article article = dto.toEntity();
        return articleRepository.save(article);
    }

    //PATCH
    @PatchMapping("/api/articles/{id}")
    public ResponseEntity<Article> update(@PathVariable Long id,
                                          @RequestBody ArticleForm dto) {
        // 1: DTO -> 엔티티
        Article article = dto.toEntity();
        log.info("id: {}, article: {}", id, article.toString());

        // 2: 타겟 조회
        Article target = articleRepository.findById(id).orElse(null);

        // 3: 잘못된 요청 처리
        if (target == null || id != article.getId()) {
            // 400, 잘못된 요청 응답!
            log.info("잘못된 요청! id: {}, article: {}", id, article.toString());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }

        // 4: 업데이트 및 정상 응답(200)
        target.patch(article);
        Article updated = articleRepository.save(target);
        return ResponseEntity.status(HttpStatus.OK).body(updated);
    }

    //DELETE
    @DeleteMapping("/api/articles/{id}")
    public ResponseEntity<Article> delete(@PathVariable Long id) {
        // 대상 찾기
        Article target = articleRepository.findById(id).orElse(null);

        // 잘못된 요청 처리
        if (target == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }

        // 대상 삭제
        articleRepository.delete(target);
        return ResponseEntity.status(HttpStatus.OK).build();
    }
}

 

package com.example.firstproject.entity;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;

import javax.persistence.*;

@Entity //DB가 해당 객체를 인식 가능 (해당 클래스로 테이블을 만든다)
@AllArgsConstructor
@NoArgsConstructor //디폴트 생성자를 추가
@ToString
@Getter
public class Article {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)//DB가 ID를 자동 생성
    private Long id;

    @Column
    private String title;

    @Column
    private String content;

    public void patch(Article article) {
        if (article.title != null)
            this.title = article.title;
        if (article.content != null)
            this.content = article.content;
        }
    }

 

package com.example.firstproject.dto;

import com.example.firstproject.entity.Article;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.ToString;

import javax.persistence.Entity;


@NoArgsConstructor
@AllArgsConstructor
@ToString
public class ArticleForm {

    private Long id;
    private String title;
    private String content;

    public Article toEntity() {

        return new Article( id, title, content);
    }
}

 

인텔리제이 오류는 아래와 같고,

org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.ARTICLE(ID) ( /* key:1 */ CAST(1 AS BIGINT), '1111', '1')"; SQL statement:
insert into article (id, content, title) values (default, ?, ?) [23505-214]

 

Talend API 오류는 아래와 같습니다.

{
"timestamp": "2022-11-01T12:34:19.732+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/api/articles"
}

아래에는 캡처본 올립니다.

 

캡처1.PNG캡처.PNG

 

먼저 비슷한 질문 해주신 분 따라서 해봤는데 안되서 질문올립니다.

spring-boot

답변 1

0

홍팍

새로 추가하는 데이터가
이미 존재하는 값의 PK로 값을 넣고 있네요

실습중인 DB가
H2 메모리 DB가 맞을까요?

스프링 부트 버전은 어떻게 되시나요?

아래의 QnA 링크도 확인해보세요

 

PS.

되도록 강의와 다른 개발환경(스프링부트 버전, 사용중인 DB)
으로 실습을 권장합니다.

23강 댓글 생성 메소드 오류

0

82

2

15.14 강 에러 문제 질문

0

55

1

21강 자율 과제중 update

0

118

2

28강 DB mysql연동 관련 질문

0

281

1

27강 관련 질문

0

198

1

22강 관련질문

0

306

2

21강 create테스트 질문

0

357

1

9강 질문 있습니다

0

280

1

로그창에 내용이 출력이 안됩니다.

0

367

1

index()함수 질문있습니다.

0

361

3

수정완료를 눌렀을때 첫번째 데이터는 전송이 안되고 다시 수정완료 버튼을 눌러야 데이터가 전송 됩니다.

0

474

1

강의와 책 질문

0

434

1

20강 질문있습니다.

0

397

1

20강에서 Article create 부분

0

289

1

16강 질문있습니다.

0

264

1

mustache의 article의 정의가 뭔가요?

0

338

2

17강 Unique index or primary key violation

1

1827

2

8강 에러 질문있습니다.

0

269

1

15강 DB연결

0

342

1

추상클래스를 사용 할 수있을까요?

0

241

1

22강 과제 질문

0

374

1

22강 질문입니다.

0

369

1

19강 create POST 500 에러

0

454

1

19강 JSON create 메서드 질문이여!!

1

541

1