代码之家  ›  专栏  ›  技术社区  ›  Paul

休眠验证器不是作为Spring存储库触发的。在单元测试中调用save()。

  •  4
  • Paul  · 技术社区  · 6 年前

    @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))
    

    我以为验证器会自动工作。我在这里做错什么了?

    1 回复  |  直到 6 年前
        1
  •  3
  •   davidxxx    6 年前


    你可以参考 Hibernate validator FAQ

    为什么我的JPA实体在调用时没有经过验证? persist() 答案是呼叫 EntityManager#flush()

    Hibernate ORM和一些其他的ORM尝试批处理尽可能多的操作 flush() 或者什么时候

    级联策略和对象图的状态。冲洗是指

    所以使用 JpaRepository.saveAndFlush() JpaRepository.save()
    或者注入 EntityManager TestEntityManager jparepository.save()。 EntityManager/TestEntityManager.flush() .

    调用 em.persist(entity) em.merge(entity)
    jparepository.saveandflush()。 jparepository.save()。 em.flush()


    saveAndFlush() ,您必须使存储库接口扩展 JpaRepository

    public interface AuditEventRepository extends  JpaRepository<AuditEventEntity, UUID> {
    

    作为 PagingAndSortingRepository ,此更改与您现有的声明保持一致。


    assertThat(saved.getLabel()).isNotNull();
    

    你想说的是 ValidationException