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.
Yes, DataNucleus JPA allows it, as well as to many other databases.
Id annotation does not belong to spring-data-mongodb module, it belongs to spring data for widely used both for spring-data-jpa and spring-data-mongodb.
MongoTemplate provides a simple way for you to save, update, and delete your domain objects and map those objects to documents stored in MongoDB. You can save, update and delete the object as shown below. MongoOperations is the interface that MongoTemplate implements.
The @Id annotation tells the mapper which property you want to use for the MongoDB _id property and the @Indexed annotation tells the mapping framework to call ensureIndex on that property of your document, making searches faster.
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
I just ran into this problem myself, it happens because you are creating the id yourself.
public Profile(String username) {
this.username = username;
}
By doing this, mongo thinks it is not a new object and doesn't use the @CreatedDate annotation. You could also use the @Document annotation instead of implementing the Persistable Class, like this:
@Document
public class Profile{}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With