【发布时间】:2018-04-13 18:17:55
【问题描述】:
我有一个简单的 Persistable 类:
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 并没有改变任何东西。
【问题讨论】:
-
它对我有用...
-
奇怪.. 2 小时我试图找出为什么它对我不起作用。我已经创建了我的实体,其 ID 为“new Profile(“username”)”,然后保存了它。你也可以这样试试吗
-
你能显示配置吗?我猜你有@EnableMongoRepositories。
-
在您的情况下,因为您始终设置用户名,所以 spring 存储库始终尝试将实体处理为更新(保存)而不是插入,因为 isNew 始终返回 false。所以 createdDate 字段永远不会被设置。我敢打赌,如果您包含 lastModified 字段,它将被设置。尝试实现
Auditable接口并在自定义 ID 的情况下自己设置审计字段。更多here -
进一步思考可能会滚动我们自己的
Auditable实现可能无法正常工作,因为 isNew 将返回 false 并且 spring 存储库将仅从实体复制 lastModifed 字段。所以看起来你必须更新 isNew 实现来区分插入和更新请求。
标签: java mongodb spring-boot spring-data-mongodb