且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当手动分配ID时,Spring Data MongoDB Annotation @CreatedDate不起作用

更新时间:2023-11-30 23:38:16

您的代码按预期工作。在您实现 Persistable 后,您可以看到 @CreatedDate 注释正在运行。

Your code is working as expected. After you've implemented Persistable you can see that @CreatedDate annotation is working.

第二次调用时,确保 createdDate null 因为该对象已存在于数据库中,并且您使用 createdDate = null 更新了该对象。正如您从 @CreatedDate 的文档中看到的那样:

Sure that createdDate is null on the second call of save because the object already exists in the database and you updated it with createdDate = null. As you can see from the documentation for @CreatedDate:


@CreatedDate注释。这标识了当实体第一次持久保存到数据库时其值设置为
的字段。

@CreatedDate annotation. This identifies the field whose value is set when the entity is persisted to the database for the first time.

所以不是要在第二次调用时用 null 覆盖 createdDate ,您应该使用 c = repository.findOne(test_id); 然后更新它。

So not to overwrite your createdDate with null on the second call you should retrieve your customer from the database with c = repository.findOne("test_id"); and then update it.