This is my entity:
@Builder
@Data
@Entity
@Table(name = "audit_log")
public class AuditEventEntity {
@Id
@GeneratedValue
private UUID id;
private long createdEpoch;
@NotNull
@Size(min = 1, max = 128)
private String label;
@NotNull
@Size(min = 1)
private String description;
}
And this is my repository:
@Repository
public interface AuditEventRepository extends PagingAndSortingRepository<AuditEventEntity, UUID> {
}
When I write the following unit test for the repository, the save is successful even though the "label" field is null!
@DataJpaTest
@RunWith(SpringRunner.class)
public class AuditRepositoryTest {
@Test
public void shouldHaveLabel() {
AuditEventEntity entity = AuditEventEntity.builder()
.createdEpoch(Instant.now().toEpochMilli())
.description(RandomStringUtils.random(1000))
.build();
assertThat(entity.getLabel()).isNullOrEmpty();
AuditEventEntity saved = repository.save(entity);
// Entity saved and didn't get validated!
assertThat(saved.getLabel()).isNotNull();
// The label field is still null, and the entity did persist.
}
@Autowired
private AuditEventRepository repository;
}
Whether I use @NotNull
or @Column(nullable = false)
the database is created with the not null
flag on the column:
Hibernate: create table audit_log (id binary not null, created_epoch bigint not null, description varchar(255) not null, label varchar(128) not null, primary key (id))
I thought the validators would work automatically. What am I doing wrong here?