【发布时间】:2018-12-06 12:08:31
【问题描述】:
这是我的实体:
@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;
}
这是我的存储库:
@Repository
public interface AuditEventRepository extends PagingAndSortingRepository<AuditEventEntity, UUID> {
}
当我为存储库编写以下单元测试时,即使“标签”字段为空,保存也是成功的!
@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;
}
无论我使用@NotNull 还是@Column(nullable = false),数据库都是使用列上的not null 标志创建的:
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))
我认为验证器会自动工作。我在这里做错了什么?
【问题讨论】:
-
@PospolitaNikita 看起来 Spring 将接受该字段上的任一注释。我都试过了,可以看到 Hibernate 在每种情况下都使用
label varchar(128) not null创建数据库。
标签: java spring validation spring-boot spring-data