本文介绍了Spring Data MongoDB-与自定义ID字段一起使用时,注释@CreatedDate不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一个简单的Persistable类:

I have a simple Persistable Class:

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

还有一个简单的存储库:

And a simple repository:

public interface ProfileRepository extends MongoRepository<Profile, String> {

}

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

My Spring Boot Application class is also annotated with @EnableMongoAuditing. But i still can't get the annotation @CreatedDate work.

ProfileRepository.save(new Profile("user1"))写入没有字段createdDate的实体.我该怎么办?

ProfileRepository.save(new Profile("user1")) writes the entity without the field createdDate. What do i do wrong?

编辑:这是我的Application类(没有@EnableMongoRepositories,但是它可以工作,因为我认为存储库位于子包中)

This is my Application class (without @EnableMongoRepositories, but it works since the repositories are in the sub-packages i guess)

@SpringBootApplication
@EnableMongoAuditing
public class Application {

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

编辑:同样添加了注释EnableMongoRepositories并没有做任何更改.

Also adding the annotation EnableMongoRepositories did not change anything.

推荐答案

您应该只将@Version字段添加到@Document类中,并启用@EnableMongoAuditing.看起来像这样:

You just ought to add @Version filed to you @Document class and left @EnableMongoAuditing enabled. It will look something like this:

@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

Here is a related issue: https://jira.spring.io/browse/DATAMONGO-946

这篇关于Spring Data MongoDB-与自定义ID字段一起使用时,注释@CreatedDate不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 05:50