IT/데이터베이스
[JPA] Null value was assigned to a property exception
데모버전
2022. 9. 18. 22:18
반응형
1. 에러 원인
- JPA를 사용해 개발을 하다 보면 database column은 nullabel 속성이지만 entity의 field는 primitive 타입으로 설정할 때가 있다.
- 그럴 때 primitive type에는 null 값을 할당할 수 없어 해당 에러가 발생한다.
2. example
- Entity 설정 code
// TestEntity.java
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class TestEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int testPriority;
}
// TestRepository.java
@Repository
public interface TestRepository extends JpaRepository<TestEntity, Long> {
}
- table 설정 (기본값이 들어 있음)
- test code
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ExtendWith(SpringExtension.class)
@DataJpaTest
class Test_20220918 {
@Autowired
private TestRepository testRepository;
@Test
void findById() {
// given
testRepository.findById(1L);
}
}
- 에러 메시지
3. 해결 방법
- 가장 간단한 방법은 primitive 타입이 아니라 reference 타입으로 변경해주면 된다.
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class TestEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Integer testPriority;
}
반응형