Reputation: 103
I am using Spring Boot to access my MongoDB database. I have an entity called User and a UserRepository to have CRUD operations. I would like that each time I add a user, it also add a creation and update date. With traditionnal SQL database and JPA, I would use @PrePersist and @PreUpdate.
What would be the best way to do it in this case ?
I paste my User code below (but it is super simple) :
public class User {
@Id
public String id;
public String username;
public String password;
}
And the UserRepository :
@RepositoryRestResource(collectionResourceRel = "users", path="users")
public interface UsersRepository extends MongoRepository<User, String>{
public User findByUsername(String username);
}
Upvotes: 1
Views: 4074
Reputation: 186
You would have to enable auditing feature and update User
domain object.
Add joda-time
maven dependency.
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.9</version>
</dependency>
Enable auditing support in spring configuration.
<mongo:auditing />
Add 2 more properties in User
.
@CreatedDate
private DateTime createdOn;
@LastModifiedDate
private DateTime updatedOn;
Please note, createdOn
only gets added for the first time when Id field is set.
Upvotes: 4