How To Configure MongoDb Collection Name For a Class in Spring Data

后端 未结 5 852
灰色年华
灰色年华 2020-12-08 15:16

I have a collection called Products in my MongoDB database, which is represented by the interface IProductPrice in my Java code. The following repo

5条回答
  •  有刺的猬
    2020-12-08 15:40

    I use static class and method in SpEL;

    public class CollectionNameHolder {
        private static final ThreadLocal collectionNameThreadLocal = new ThreadLocal<>();
    
        public static String get(){
            String collectionName = collectionNameThreadLocal.get();
            if(collectionName == null){
                collectionName = DataCenterApiConstant.APP_WECHAT_DOCTOR_PATIENT_COLLECTION_NAME;
                collectionNameThreadLocal.set(collectionName);
            }
            return collectionName;
        }
    
        public static void set(String collectionName){
            collectionNameThreadLocal.set(collectionName);
        }
    
        public static void reset(){
            collectionNameThreadLocal.remove();
        }
    }
    

    In Entity class ,@Document(collection = "#{T(com.test.data.CollectionNameHolder).get()}")

    And then ,use

    CollectionNameHolder.set("testx_"+pageNum) 
    

    in Service , and

    CollectionNameHolder.reset();
    

    Hope it helps you.

提交回复
热议问题