我创建了以下实体并使用 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
仍然不为空?null
lastModified
编辑
我将Topic.createdAt
和的类型更改Topic.lastModified
为Instant
,但没有用。
另外,我添加了以下方法,我猜它应该为Instant
字段提供值:
@Bean
public AuditorAware<Instant> instantAuditorAware() {
return () -> Optional.of(Instant.now());
}
可悲的是,虽然该方法被调用,createdAt
但仍然是null
.