• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

19강 Talend API POST 500 에러

22.11.01 21:43 작성 조회수 780

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

 

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

답변 1

답변을 작성해보세요.

0

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

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

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

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

 

PS.

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