Set Dynamic table names in model class

What is model class in java

Model class represents the table in the database. Spring Data JPA dependency used for relational database and Spring data mongodb dependency used for non-relational database which is no-sql.

Configuration with Document annotation

The Document annotation available since Spring Data version 1.9, It's specific for MongoDB.

The default behavior considers the collection name to be the same as the class name but starting with lower case just need to add the Document annotation.

One disadvantage is that if we decide to change our database naming conventions, we'll need to refactor all our classes.

By using the document annotation we can override the default behavior with the collection property, Since this property is an alias for the value property.

@Document(collection = "person_details")
public class PersonDetails {
    @Id
    private String id;

    private String name;

    private String age;

    // getters and setters
}

This is the simplest way to configure a collection name with Spring Data.

Using Configuration Property with SpEL:

This combination can help do things that are not possible using the Document annotation alone. We'll start with an application-specific property that we want to reuse among our classes.

let's add property into the application.properties file

collection.personDetails=person_details

Now, let's reference it with SpEL via the environment bean to create our next class

@Document("#{@environment.getProperty('collection.personDetails')}")
public class PersonDetails {
    @Id
    private String id;
    private String name;
     private String age;

    // getters and setters
}

Instead of properties file we can configure it from any of the constants file.

Constants.java

public static final string COLLECTION.PERSON_DETAILS=person_details;

then apply Regular expression like below in the model class.

@Document("#{Constants.COLLECTION.PERSON_DETAILS}")
public class PersonDetails {
    @Id
    private String id;
    private String name;
     private String age;

    // getters and setters
}

Instead of maintaining collection names statically we can maintain one constant class so from that we can access the table names dynamically using regular expression.

THANK YOU...