Как использовать репозиторий данных spring для mongodb для извлечения данных из репозиториев mongo с динамическими именами полей?

Я использую Spring Data 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?

Чтобы быть уверенным, я правильно понял, имена, которые не известны заранее, являются именами атрибутов класса SupplierResponse?

charlycou 22.05.2019 14:37

Класс @charlycou SupplierResponse имеет фиксированные имена переменных, например, имя поставщика, но коллекция SupplierResponse в монго может иметь другое имя, например supp_name, так как мне их сопоставить. скажем, у меня есть сопоставление suppliername=supp_name, но как мне получить все поля из коллекции с помощью MongoRepository, так как у него должны быть те же имена переменных, что и у полей, присутствующих в коллекции

Akshay Naik 22.05.2019 17:28

Я предлагаю вам использовать пользовательский конвертер. Я отвечу на ваш вопрос этим предложением.

charlycou 22.05.2019 17:45
Использование JavaScript и MongoDB
Использование JavaScript и MongoDB
Сегодня я собираюсь вкратце рассказать о прототипах в JavaScript, а также представить и объяснить вам работу с базой данных MongoDB.
0
3
1 715
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 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;
    }
}

когда я добавляю класс конфигурации, я получаю сообщение об ошибке ниже. Вызвано: org.springframework.beans.factory.BeanCreationException: ошибка создания bean-компонента с именем «mongoDbFactory», определенным в ресурсе пути к классу [com/example/demo/MyApplicationConfig.class]: создание экземпляра Bean через заводской метод не удался; вложенным исключением является org.springframework.beans.BeanInstantiationException: не удалось создать экземпляр [org.springframework.data.mongodb.MongoDbFactory]: фабричный метод 'mongoDbFactory' вызвал исключение; вложенным исключением является java.lang.IllegalArgumentException: MongoClient не может быть нулевым!

Akshay Naik 28.05.2019 09:58

потому что ниже приведены методы по умолчанию для AbstractMongoConfiguration public MongoClient mongoClient() { // TODO Автоматически сгенерированный метод-заглушка return null; } protected String getDatabaseName() { // Автоматически сгенерированный метод TODO return null; }

Akshay Naik 28.05.2019 10:00

Вы можете попробовать, не продлевая AbstractMongoConfiguration. Я не знаю, переопределит ли этот компонент поведение по умолчанию. В противном случае вы можете переопределить AbstractMongoConfiguration - см. редактирование

charlycou 28.05.2019 10:03

Другие вопросы по теме