如何使用mongodb的spring数据存储库从具有动态字段名称的mongo存储库中获取数据?

时间:2019-05-22 11:25:20

标签: mongodb spring-boot spring-data-mongodb

我正在使用spring数据JPA从mongoDB中获取数据。

public interface SupplierResponseRepo extends MongoRepository<SupplierResponse, String>  {}

@Document
public class SupplierResponse{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private String supplierResponseId;
    private String orderId;
    private String orderName;
}

上面的代码一直工作到固定所有字段名称,现在可以有多个字段,并且它们的名称事先未知,我希望提取所有字段。 有什么办法可以做同样的事情,就像我可以将任何泛型类型传递给MongoRepository接口并获取所有列一样。

我在mongoTemplate上也遇到了同样的问题,但是后来使用DBObject解决了。

mongoTemplate.find(query, DBObject.class,"supplier");

MongoRepository也有类似的选择吗?

1 个答案:

答案 0 :(得分:1)

您可以使用自定义Converter类通过MongoRepository获取数据。由于它是来自Mongodb的数据,因此您需要在Spring Data应用程序中进行映射,因此您需要使用@ReadingConverter

/**
 * @ReadingConverter: Spring data mongodb annotation to enable the class to handle the mapping of DBObject into Java
 * Objects
 */
@ReadingConverter
public class SupplierResponseConverter implements Converter<Document, SupplierResponse> {
    /**
     * Map DBObject to SupplierResponse inherited class according to the MongoDB document attributes
     * @param source MongoDB Document object
     * @return SupplierResponse Object
     */
    @Override
    public SupplierResponse convert(Document source) {
        if (source.get("supp_id") != null) {
            SupplierResponse supplierResponse = new SupplierResponse();
            supplierResponse.setSupplierId(source.get("supp_id", String.class)
        }
        //repeat this operation for all your attribute in order to map them according to a condition of your choice
}

然后,您需要在@Configuration类中启用自定义转换器类。您可以通过这种方式进行。通过扩展AbstractMongoConfiguration,您将不得不重写一些其他方法。

/**
 * @Configuration: allow to register extra Spring beans in the context or import additional configuration classes
 */
@Configuration
public class DataportalApplicationConfig extends AbstractMongoConfiguration {

    //@Value: inject property values into components
    @Value("${spring.data.mongodb.uri}")
    private String uri;
    @Value("${spring.data.mongodb.database}")
    private String database;

    /**
     * Configure the MongoClient with the uri
     *
     * @return MongoClient.class
     */
    @Override
    public MongoClient mongoClient() {
        return new MongoClient(new MongoClientURI(uri));
    }

    /**
     * Database name getter
     *
     * @return the database the query will be performed
     */
    @Override
    protected String getDatabaseName() {
        return database;
    }

    /**
     * @Bean: explicitly declare that a method produces a Spring bean to be managed by the Spring container.
     * Configuration of the custom converter defined for the entity schema.
     * @return MongoCustomConversions.class
     */
    @Bean
    @Override
    public MongoCustomConversions customConversions() {
        List<Converter<?, ?>> converterList = new ArrayList<>();
        converterList.add(new ContactReadConverter());
        converterList.add(new GeometryGeoJSONReadConverter());
        converterList.add(new SamplingFeatureReadConverter());
        converterList.add(new SensorReadConverter());
        return new MongoCustomConversions(converterList);
    }

    /**
     * @Bean: explicitly declare that a method produces a Spring bean to be managed by the Spring container.
     * Configuration of the MongoTemplate with the newly defined custom converters. The MongoTemplate class is the
     * central class of Spring’s MongoDB support and provides a rich feature set for interacting with the database. The
     * template offers convenience operations to create, update, delete, and query MongoDB documents and provides a
     * mapping between your domain objects and MongoDB documents.
     *
     * @return MongoTemplate.class
     */
    @Bean
    @Override
    public MongoTemplate mongoTemplate() {
        MongoTemplate mongoTemplate = new MongoTemplate(mongoClient(), getDatabaseName());
        MappingMongoConverter mongoMapping = (MappingMongoConverter) mongoTemplate.getConverter();
        mongoTemplate.setWriteResultChecking(WriteResultChecking.EXCEPTION);
        mongoTemplate.setWriteConcern(WriteConcern.MAJORITY);
        mongoMapping.setCustomConversions(customConversions()); // tell mongodb to use the custom converters
        mongoMapping.afterPropertiesSet();
        return mongoTemplate;
    }
}