Spring Data MongoDB - 使用自定义 Id 字段时,注释 @CreatedDate 不起作用

akc*_*soy 7 java mongodb spring-data-jpa spring-data-mongodb spring-boot

我有一个简单的持久化类:

public class Profile implements Persistable<String>{

    @Id
    private String username;

    @CreatedDate
    public Date createdDate;

    public Profile(String username) {
        this.username = username;
    }

    @Override
    public String getId() {
        return username;
    }

    @Override
    public boolean isNew() {
        return username == null;
    }
}
Run Code Online (Sandbox Code Playgroud)

和一个简单的存储库:

public interface ProfileRepository extends MongoRepository<Profile, String> {

}
Run Code Online (Sandbox Code Playgroud)

我的 Spring Boot Application 类也用 @EnableMongoAuditing 进行了注释。但我仍然无法获得注释 @CreatedDate 工作。

ProfileRepository.save(new Profile("user1")) 写入没有字段 createdDate 的实体。我做错了什么?

编辑:这是我的应用程序类(没有@EnableMongoRepositories,但它可以工作,因为存储库在我猜的子包中)

@SpringBootApplication
@EnableMongoAuditing
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:同时添加注释 EnableMongoRepositories 没有改变任何东西。

Bar*_*wez 5

我自己刚刚遇到了这个问题,这是因为您自己创建了 id。

public Profile(String username) {
        this.username = username;
    }
Run Code Online (Sandbox Code Playgroud)

通过这样做,mongo 认为它不是一个新对象并且不使用 @CreatedDate 注释。您还可以使用 @Document 批注而不是实现 Persistable 类,如下所示:

@Document
public class Profile{}
Run Code Online (Sandbox Code Playgroud)


pov*_*nko 5

你只应该添加@Version到你的@Document班级然后离开@EnableMongoAuditing

@Document
public class Profile implements Persistable<String>{

     @Version      
     private Long version;
    
     @Id
     private String username;

     @CreatedDate
     public Date createdDate;

     public Profile(String username) {
         this.username = username;
     }

     @Override
     public String getId() {
         return username;
     }

     @Override
     public boolean isNew() {
         return username == null;
     }
 }
Run Code Online (Sandbox Code Playgroud)

这是一个相关的问题:https : //jira.spring.io/browse/DATAMONGO-946