500 NULL not allowed for column \"ID\"

응큼한포도·2023년 12월 28일

트러블 슈팅

목록 보기
1/2

post man으로 확인

글 쓰기란에 글을 써도 DB에 저장되지 않아서 post man을 통해 확인한다.

ID에 NULL 값이 들어간걸로 보아 dto에 문제가 있는 것 같다.

TEST로 확인


@WebMvcTest(ArticleApiController.class)
public class ArticleApiControllerTest {

    @Autowired
    private WebApplicationContext context;

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private ArticleService articleService;

    @Test
    @DisplayName("createArticle: 블로그 글 생성 성공한다.")
    @WithMockUser(username = "testuser", roles = {"USER"})
    public void addArticle() throws Exception {
        // given
        AddArticleRequest requestForm = AddArticleRequest.builder()
                .title("Test Title")
                .content("Test Content")
                .build();

        Article createdArticle = Article.builder()
                .id(1L)
                .title("Test Title")
                .content("Test Content")
                .build();

        given(articleService.create(any(AddArticleRequest.class))).willReturn(createdArticle);

        // when
        mockMvc.perform(MockMvcRequestBuilders.post("/api/articles")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(asJsonString(requestForm))
                        .with(SecurityMockMvcRequestPostProcessors.csrf())) // CSRF 토큰 추가
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.is(1)))
                .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("Test Title")))
                .andExpect(MockMvcResultMatchers.jsonPath("$.content", Matchers.is("Test Content")));
    }

다음과 같이 mock객체를 이용하여 테스트를 해본 결과
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaAuditingHandler': Cannot resolve reference to bean 'jpaMappingContext' while setting constructor argument 란 에러 메세지를 얻었다.
찾아보니

첫째로, 'jpaMappingContext' 빈을 생성하는 중에 JPA 메타모델이 비어 있을 경우 발생할 수 있어요. 이는 JPA 엔터티 클래스들이 스캔되지 않거나, 올바르게 매핑되지 않은 경우에 발생할 수 있어요.

또 다른 가능성은 'jpaAuditingHandler' 빈을 생성하는 중에 'jpaMappingContext' 빈에 대한 참조를 해결하지 못하는 상황일 수 있어요. 이 경우 JPA 설정이나 엔터티 클래스들의 구성이 잘못되었을 수 있습니다.

라고 gpt가 대답해주었다.

@NoArgsConstructor(access = AccessLevel.PROTECTED)
@EntityListeners(AuditingEntityListener.class)
@Entity
@Getter
public class Article {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name ="id", updatable = false)
    private Long id;

    @Column(name = "title", nullable = false)
    private String title;

    @Column(name = "content", nullable = false)
    private String content;

    @CreatedDate
    @Column(name = "created_at")
    private LocalDateTime createdAt;

    @LastModifiedDate
    @Column(name = "updated_at")
    private LocalDateTime updatedAt;

    @Builder
    public Article(String title, String content) {
        this.title = title;
        this.content = content;
    }

    public void update(String title, String content) {
        this.title = title;
        this.content = content;
    }
}

엔티티 클래스의 @GeneratedValue(strategy = GenerationType.IDENTITY)의 부분을 @GeneratedValue(strategy = GenerationType.AUTO) 또는 SEQUENCE로 바꿔주니 해결되었다.

이유?

데이터 베이스의 종류와 버전에서 호환이 재대로 되지 않아서 에러가 나는 경우가 있다고 한다. 보통 AUTO_INCREMENT 설정이 데이터베이스에 안 돼 있으면 나타나는 오류라고 한다.

0개의 댓글