Как использовать репозиторий данных Spring для mongodb для получения данных из репозиториев mongo с динамическими именами полей? - PullRequest
0 голосов
/ 22 мая 2019

Я использую пружинные данные 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 Ответ

1 голос
/ 22 мая 2019

Вы можете использовать пользовательский класс 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;
    }
}
...