gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:11:58 24 4
gpt4 key购买 nike

我有一个简单的持久类:

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;
}
}

还有一个简单的存储库:

public interface ProfileRepository extends MongoRepository<Profile, String> {

}

我的 Spring Boot 应用程序类也使用 @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);
}
}

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

最佳答案

只需将 @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;
}
}

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

关于java - Spring Data MongoDB - 注释@CreatedDate 在与自定义 Id 字段一起使用时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47054719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com