본문 바로가기
Spring/DB연동

JPA Entity에 Validation

by doriver 2025. 2. 22.
implementation 'org.springframework.boot:spring-boot-starter-validation'

Entity가 영속성을 가지게될때 validation annotation적용됨

예) save메서드에서 em.persist(entity) 실행중에 validation annotation검증하여, 검증 실패하면 예외 던짐

 

@Column(nullable = false)  vs  @NotNull

@NotNull이 붙어있으면 DDL 생성시 not null로 생성

Hibernate는 엔티티에 적용된 Bean Validation어노테이션 역시 DDL로 변환
만약 이 기능을 비활성화하려면, application.properties에 다음 한 줄을 추가하면 된다.

spring.jpa.properties.hibernate.validator.apply_to_ddl=false

 

@NotNull 어노테이션을 쓰면, 데이터베이스에 SQL 쿼리를 보내기 전에 예외가 발생한다.
JPA의 Repository 인터페이스가 잘못된 Entity를 저장할 때, ConstraintViolationException을 발생시킨다.
(그 때문에, @Valid나 @Validated 없이도 엔티티를 자연스럽게 검증할 수 있다)

 

@Column(nullable = false)의 경우는
null을 넣은 엔티티가 Repository에 전달되고, DB에 넘어간 뒤에
예외가 발생해 위험한 오류를 맞을 수 있다.

 

 

https://kafcamus.tistory.com/15

 

[JPA] nullable=false와 @NotNull 비교, Hibernate Validation

오늘은 다음의 고민 때문에 글을 작성하게 되었다. JPA에서 DDL을 자동으로 생성할 수 있는데, 이 때 not null 옵션은 어떻게 붙이나? JPA의 엔티티 객체에 @NotNull 검증 어노테이션을 주면 어떻게 되나

kafcamus.tistory.com

 

'Spring > DB연동' 카테고리의 다른 글

@Transactional 01  (0) 2025.02.23
entity에서 원시타입 vs Wrapper클래스  (0) 2025.02.22
Entity클래스 어노테이션  (0) 2025.02.20
JPA Entity 관련 01  (0) 2025.01.17
JPA 에러 모음 01  (0) 2025.01.16