我有一个简单的持久课程:
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类也被注释为@EnableMongoAudting.,但是我仍然无法得到注释@CreatedDate。
ProfileRepository.save(新配置文件(“user1”))在没有字段createdDate的情况下写入实体。我做错什么了?
编辑:--这是我的应用程序类(没有@EnableMongoRepositories,但它可以工作,因为存储库在我猜的子包中)
@SpringBootApplication
@EnableMongoAuditing
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
编辑:也添加了注释EnableMongoRepositories没有改变任何东西。
发布于 2018-08-15 13:04:08
只需将@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
发布于 2017-11-03 10:15:03
我自己也遇到了这个问题,这是因为你自己正在创建id。
public Profile(String username) {
this.username = username;
}
通过这样做,mongo认为它不是一个新对象,并且不使用@CreatedDate注释。您还可以使用@Document注释,而不是实现Persistable类,如下所示:
@Document
public class Profile{}
发布于 2021-01-13 22:17:31
正如Spring发布DATAMONGO-946中描述的那样,创建的日期功能使用isNew()
方法来确定是否应该设置创建的日期,因为该实体是新的。在这种情况下,您的isNew
方法总是返回false,因为username
总是被设置的。
该问题的评论提出了解决这一问题的两种可能的解决办法。
Persistable
解
第一个选项是修复isNew
策略,以便它正确地注册新对象。注释中建议的一种方法是更改实现以检查createdDate
字段本身,因为它只应该设置在非新对象上。
@Override
public boolean isNew() {
return createdDate == null;
}
持久实体解决方案
第二个选择是从实现Persistable
改为使用持久实体,并使用@Version
注释在持久化的MongoDB实体中注入version
属性。注意,这将改变数据的持久化方式,因为它向数据中添加了一个自动递增的version
字段。
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class Profile {
@Id
private String username;
@CreatedDate
public Date createdDate;
@Version
public Integer version;
public Profile(String username) {
this.username = username;
}
}
https://stackoverflow.com/questions/47054719
复制相似问题