Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

java - Spring Data MongoDB - Annotation @CreatedDate does not work while using with custom Id field

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> {

}

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")) writes the entity without the field createdDate. What do i do wrong?

EDIT: 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);
    }
}

EDIT: Also adding the annotation EnableMongoRepositories did not change anything.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

simply just add @Version field to you @Document class and leave @EnableMongoAuditing i.e.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...