1

我创建了以下实体并使用 h2 对其进行了测试:

@Getter
public class Topic {

    @Id
    private long id;

    private final Title title;

    @CreatedDate
    private LocalDateTime createdAt;

    @LastModifiedDate
    private LocalDateTime lastModified;

    // ...
}

TopicRepository一个空接口。

以下测试失败,错误createdAt为 null:

@RunWith(SpringRunner.class)
@SpringBootTest
public class BasicRepositoryTests {

    @Autowired
    TopicRepository topicRepository;

    @Test
    public void topicRepositoryWorks() {
        val topic = new Topic();
        val savedTopic = topicRepository.save(topic);

        assertEquals(1, topicRepository.count());
        assertNotNull(savedTopic.getLastModified(), "lastModified must be set");
        assertNotNull(savedTopic.getCreatedAt(), "createdAt must be set");

        topicRepository.delete(savedTopic);

        assertEquals(0, topicRepository.count());
    }

}

@SpringBootApplication我的应用程序用和注释@EnableJdbcAuditing

另一方面,为什么createdAt仍然不为空?nulllastModified

编辑

我将Topic.createdAt和的类型更改Topic.lastModifiedInstant,但没有用。

另外,我添加了以下方法,我猜它应该为Instant字段提供值:

@Bean
public AuditorAware<Instant> instantAuditorAware() {
    return () -> Optional.of(Instant.now());
}

可悲的是,虽然该方法被调用,createdAt但仍然是null.

4

1 回答 1

3

审核注释只考虑聚合根。如果作为聚合的一部分但不是聚合根的实体需要审计信息,这可以通过在聚合根中实现它来完成,聚合根应该管理对其和聚合实体的所有更改。

虽然问题中发布的源代码表明您实际上正在查看聚合根目录,但您通过 Github 提供的代码显示根目录上的注释工作正常,但非根实体上的注释与上述不同。

你不需要一个AuditorAware豆子。只需要@CreatedBy@LastModifiedBy

于 2019-06-13T05:50:31.027 回答