mongodbspring-bootspring-data-mongodb

Auto set fields in spring data mongodb


I have a Base Entity class which all my Spring Data MongoDB classes extend, I want to have a few basic fields (check below) which need to be auto-set/auto-updated, what's the cleanest way to achieve this?

public class BaseEntity {
    @Id
    private ObjectId id;
    private Instant createdOn;
    private Instant updatedOn;
}

I'm using Spring Boot 3.x and Java 17.


Solution

  • Yes, you can achieve this using Spring Data MongoDB support. Here's how to set up:

    1 - Define a base class with auditing annotations:

    public class BaseEntity {
    
        @Id
        private ObjectId id;
    
        @CreatedDate
        private Instant createdOn;
    
        @LastModifiedDate
        private Instant updatedOn;
    }
    

    Your entities can simply extend this base class:

    @Document(collection = "concrete")
    public class ConcreteEntity extends BaseEntity {
        ...
    }
    

    2 - Enable auditing in your main application class:

    @SpringBootApplication
    @EnableMongoAuditing
    public class ShowcaseApplication {
        public static void main(String[] args) {
           SpringApplication.run(ShowcaseApplication.class, args);
        }
    }
    

    That's it! Spring will automatically populate createdOn and updatedOn when the document is inserted.