spring boot mongodb 多数据源 自动下划线转驼峰

mongoDB | 2020-08-20 09:01:00

之前研究过《springBoot mybatis 多数据源 下划线转驼峰》,这次再来看看spring boot mongodb 多数据源 自动下划线转驼峰。

一般数据库的字段我们都习惯用下划线,java代码里面习惯使用驼峰,将下划线自动映射驼峰字段效率很高。

1.mongodb单个数据源下划线转驼峰

spring.data.mongodb.uri=mongodb://192.168.1.191:29000,192.168.1.192:29000,192.168.1.193:29000/database
spring.data.mongodb.field-naming-strategy=org.springframework.data.mapping.model.SnakeCaseFieldNamingStrategy

2.mongodb多数据下划线转驼峰配置

@Configuration
public class EcgMongodbDatasource {

    @Primary
    @Bean(name = "ecgMongodbProperties")
    @ConfigurationProperties(prefix="spring.data.mongodb.testmongodb")
    public MongoProperties ecgMongodbProperties() {
        return new MongoProperties();
    }

    @Primary
    @Bean(name = "ecgMongodbTemplate")
    public MongoTemplate ecgMongodbTemplate(){
        MongoDbFactory mongoDbFactory=new SimpleMongoClientDbFactory(ecgMongodbProperties().getUri());
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
        MongoMappingContext mongoMappingContext=new MongoMappingContext();
		//下划线转驼峰
        mongoMappingContext.setFieldNamingStrategy(new SnakeCaseFieldNamingStrategy());
        MongoConverter mongoConverter = new MappingMongoConverter(dbRefResolver,mongoMappingContext);
        return new MongoTemplate(mongoDbFactory,mongoConverter);
    }
}

 

登录后即可回复 登录 | 注册
    
  • houyong
    houyong

    另外更专业精简灵活的mongodb 多数据源写法

    spring.data.mongodb.ecgmongodb.uri=mongodb://192.168.1.191:29000,192.168.1.192:29000,192.168.1.193:29000/database
    spring.data.mongodb.ecgmongodb.field-naming-strategy=org.springframework.data.mapping.model.SnakeCaseFieldNamingStrategy
    @Primary
    @Configuration
    @ConfigurationProperties(prefix="spring.data.mongodb.ecgmongodb")
    public class EcgMongodbDatasource extends MongoProperties {
    
        @Primary
        @Bean(name = "ecgMongodbTemplate")
        public MongoTemplate ecgMongodbTemplate(){
            MongoDbFactory mongoDbFactory=new SimpleMongoClientDbFactory(this.getUri());
            DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
            MongoMappingContext mongoMappingContext=new MongoMappingContext();
            if(this.getFieldNamingStrategy()!=null) {
                FieldNamingStrategy fieldNamingStrategy = (FieldNamingStrategy) BeanUtils.instantiateClass(this.getFieldNamingStrategy());
                mongoMappingContext.setFieldNamingStrategy(fieldNamingStrategy);
            }
            MongoConverter mongoConverter = new MappingMongoConverter(dbRefResolver,mongoMappingContext);
            return new MongoTemplate(mongoDbFactory,mongoConverter);
        }
    }

     

关注编程学问公众号