java - Insert 上没有写@CreatedDate 注释的字段,@LastModifiedDate 是

标签 java spring spring-data auditing spring-data-jdbc

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

@Getter
public class Topic {

    @Id
    private long id;

    private final Title title;

    @CreatedDate
    private LocalDateTime createdAt;

    @LastModifiedDate
    private LocalDateTime lastModified;

    // ...
}

TopicRepository 是一个空接口(interface)。

以下测试失败,并出现 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仍然是null,而lastModified却不是null?

编辑

我将 Topic.createdAtTopic.lastModified 的类型更改为 Instant,但不起作用。

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

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

遗憾的是,尽管该方法被调用,createdAt 仍然是 null

最佳答案

仅考虑聚合根的审核注释。如果需要对属于聚合但不是聚合根的实体进行审核信息,可以通过在聚合根中实现它来完成,聚合根应该管理对其和聚合实体的所有更改。

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

您不需要 AuditorAware bean。 仅 @CreatedBy@LastModifiedBy 需要此值。

关于java - Insert 上没有写@CreatedDate 注释的字段,@LastModifiedDate 是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56542700/

相关文章:

java - 如何获取公共(public)类中注入(inject)的bean的值

java - 取消java上的复制操作

java - 创建重试模板以在连接超时和读取超时时重试

java - JPA 2.1 persistence.xml 文件中的多个持久性单元

spring-data - Spring Data PageImpl总元素错误

Spring Data Cassandra : "No property findAll for type User"

java - Scala、Spring、WebFlow、Hibernate 和 Maven 或 Java、Spring、WebFlow、Hibernate 和 Maven

Java 错误 : Cannot make a static reference to the non-static method

spring - 如何检查Grails Rest Client返回的内容类型

java - Spring 启动配置 : how to return always same random value when referenced?