Spring Data MongoDB Repository with custom collection name

后端 未结 4 1056
别那么骄傲
别那么骄傲 2021-01-06 01:18

I am using Spring Data for MongoDB and I need to be able to configure collection at runtime.

My repository is defined as:

@Repository
public interfac         


        
4条回答
  •  长发绾君心
    2021-01-06 01:31

    define your entity class like

    @Document(collection = "${EventDataRepository.getCollectionName()}")
    public class EventData implements Serializable {
    

    Define a custom repository interface with getter and setter methods for "collectionName"

    public interface EventDataRepositoryCustom {
    
        String getCollectionName();
    
        void setCollectionName(String collectionName);
    }
    

    provide implementation class for custom repository with "collectionName" implementation

    public class EventDataRepositoryImpl implements EventDataRepositoryCustom{
    
        private static String collectionName = "myCollection";
    
        @Override
        public String getCollectionName() {
            return collectionName;
        }
    
        @Override
        public void setCollectionName(String collectionName) {
            this.collectionName = collectionName;
        }
    }
    

    Add EventDataRepositoryImpl to the extends list of your repository interface in this it would look like

    @Repository
    public interface EventDataRepository extends MongoRepository, EventDataRepositoryImpl  {
    }
    

    Now in your Service class where you are using the MongoRepository set the collection name, it would look like

    @Autowired
    EventDataRepository  repository ;
    
    repository.setCollectionName("collectionName");
    

提交回复
热议问题