当前位置:   article > 正文

springboot集成 mongodb以及mongodb简单工具类_springboot实现 mongo工具类

springboot实现 mongo工具类

前言

springboot集成 mongodb 有开箱即用的starter 因此集成还是很方便的

集成

  • 添加依赖
  <!--mongodb-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
  
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 添加配置
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mydatabase
  • 1
  • 2
  • 3

使用

直接注入

@Autowired
 private MongoTemplate mongoTemplate;
  • 1
  • 2

封装的简单工具类

public interface MongoRepository {

    MongoOperations getMongoTemplate();

    /**
     * 获取集合
     *
     * @param collectionName 集合
     * @return MongoCollection
     */

    MongoCollection<Document> getCollection(String collectionName);


    MongoCollection<Document> getCollection(Query query, String collectionName);

    /**
     * 插入
     *
     * @param collectionName collectionName
     * @param doc            doc
     */
    void insert(String collectionName, Document doc);

    /**
     * 更新文档
     *
     * @param collectionName collectionName
     * @param filter         filter
     * @param updateDoc      文档
     * @return long
     */
    long update(String collectionName, Bson filter, Document updateDoc);

    /**
     * 统计
     *
     * @param collectionName collectionName
     * @param filter         filter
     * @return long
     */
    long count(String collectionName, Bson filter);

    /**
     * 统计
     *
     * @param collectionName collectionName
     * @param filter         filter
     * @return long
     */
    long countByLimit(String collectionName, Integer limit, Bson filter);

    /**
     * 去重
     *
     * @param collectionName collectionName
     * @param filter         filter
     * @param fieldName      fieldName
     * @return long
     */
    long distinctCount(String collectionName, Bson filter, String fieldName);

    /**
     * 根据指定的管道聚合文档
     *
     * @param collectionName collectionName
     * @param pipeline       pipeline
     * @return AggregateIterable
     */
    AggregateIterable<Document> aggregate(String collectionName, List<Bson> pipeline);

    /**
     * 查找
     *
     * @param collectionName collectionName
     * @param filter         filter
     * @return FindIterable
     */
    FindIterable<Document> find(String collectionName, Bson filter);

    /**
     * 获取实体类对应的集合名称
     *
     * @param entityClass entityClass
     * @return String
     */
    String getCollectionName(Class<?> entityClass);

    //新增api 

    /**
     * Insert the object into the collection for the entity type of the object to save.
     * <br />
     * The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}.
     * <br />
     * If your object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a
     * String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your
     * property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. See
     * <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation" > Spring's
     * Type Conversion"</a> for more details.
     * <br />
     * Insert is used to initially store the object into the database. To update an existing object use the save method.
     * <br />
     * The {@code objectToSave} must not be collection-like.
     *
     * @param objectToSave the object to store in the collection. Must not be {@literal null}.
     * @return the inserted object.
     * @throws IllegalArgumentException                          in case the {@code objectToSave} is collection-like.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link org.springframework.data.mongodb.core.MongoOperations#getCollectionName(java.lang.Class)} from the given object type.
     */
    <T> T insert(T objectToSave);

    /**
     * Insert the object into the specified collection.
     * <br />
     * The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. Unless
     * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
     * <br />
     * Insert is used to initially store the object into the database. To update an existing object use the save method.
     * <br />
     * The {@code objectToSave} must not be collection-like.
     *
     * @param objectToSave   the object to store in the collection. Must not be {@literal null}.
     * @param collectionName name of the collection to store the object in. Must not be {@literal null}.
     * @return the inserted object.
     * @throws IllegalArgumentException in case the {@code objectToSave} is collection-like.
     */
    <T> T insert(T objectToSave, String collectionName);

    /**
     * Insert a Collection of objects into a collection in a single batch write to the database.
     *
     * @param batchToSave the batch of objects to save. Must not be {@literal null}.
     * @param entityClass class that determines the collection to use. Must not be {@literal null}.
     * @return the inserted objects that.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link org.springframework.data.mongodb.core.MongoOperations#getCollectionName(java.lang.Class)} from the given type.
     */
    <T> Collection<T> insert(Collection<? extends T> batchToSave, Class<?> entityClass);

    /**
     * Insert a batch of objects into the specified collection in a single batch write to the database.
     *
     * @param batchToSave    the list of objects to save. Must not be {@literal null}.
     * @param collectionName name of the collection to store the object in. Must not be {@literal null}.
     * @return the inserted objects that.
     */
    <T> Collection<T> insert(Collection<? extends T> batchToSave, String collectionName);

    /**
     * Insert a mixed Collection of objects into a database collection determining the collection name to use based on the
     * class.
     *
     * @param objectsToSave the list of objects to save. Must not be {@literal null}.
     * @return the inserted objects.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link org.springframework.data.mongodb.core.MongoOperations#getCollectionName(java.lang.Class)} for the given objects.
     */
    <T> Collection<T> insertAll(Collection<? extends T> objectsToSave);

    /**
     * Save the object to the collection for the entity type of the object to save. This will perform an insert if the
     * object is not already present, that is an 'upsert'.
     * <br />
     * The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. Unless
     * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
     * <br />
     * If your object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a
     * String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your
     * property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. See
     * <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation" > Spring's
     * Type Conversion"</a> for more details.
     * <br />
     * The {@code objectToSave} must not be collection-like.
     *
     * @param objectToSave the object to store in the collection. Must not be {@literal null}.
     * @return the saved object.
     * @throws IllegalArgumentException                          in case the {@code objectToSave} is collection-like.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link org.springframework.data.mongodb.core.MongoOperations#getCollectionName(java.lang.Class)} from the given object type.
     */
    <T> T save(T objectToSave);

    /**
     * Save the object to the specified collection. This will perform an insert if the object is not already present, that
     * is an 'upsert'.
     * <br />
     * The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. Unless
     * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
     * <br />
     * If your object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a
     * String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your
     * property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API.
     * See <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation">Spring's Type Conversion</a> for more details.
     * <br />
     * The {@code objectToSave} must not be collection-like.
     *
     * @param objectToSave   the object to store in the collection. Must not be {@literal null}.
     * @param collectionName name of the collection to store the object in. Must not be {@literal null}.
     * @return the saved object.
     * @throws IllegalArgumentException in case the {@code objectToSave} is collection-like.
     */
    <T> T save(T objectToSave, String collectionName);

    /**
     * Map the results of an ad-hoc query on the collection for the entity class to a single instance of an object of the
     * specified type.
     * <br />
     * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless
     * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
     * <br />
     * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
     * feature rich {@link Query}.
     *
     * @param query       the query class that specifies the criteria used to find a record and also an optional fields
     *                    specification.
     * @param entityClass the parametrized type of the returned list.
     * @return the converted object.
     */
    @Nullable
    <T> T findOne(Query query, Class<T> entityClass);

    /**
     * Map the results of an ad-hoc query on the specified collection to a single instance of an object of the specified
     * type.
     * <br />
     * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless
     * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
     * <br />
     * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
     * feature rich {@link Query}.
     *
     * @param query          the query class that specifies the criteria used to find a record and also an optional fields
     *                       specification.
     * @param entityClass    the parametrized type of the returned list.
     * @param collectionName name of the collection to retrieve the objects from.
     * @return the converted object.
     */
    @Nullable
    <T> T findOne(Query query, Class<T> entityClass, String collectionName);

    /**
     * Determine result of given {@link Query} contains at least one element. <br />
     * <strong>NOTE:</strong> Any additional support for query/field mapping, etc. is not available due to the lack of
     * domain type information. Use {@link #exists(Query, Class, String)} to get full type specific support.
     *
     * @param query          the {@link Query} class that specifies the criteria used to find a record.
     * @param collectionName name of the collection to check for objects.
     * @return {@literal true} if the query yields a result.
     */
    boolean exists(Query query, String collectionName);

    /**
     * Determine result of given {@link Query} contains at least one element.
     *
     * @param query       the {@link Query} class that specifies the criteria used to find a record.
     * @param entityClass the parametrized type.
     * @return {@literal true} if the query yields a result.
     */
    boolean exists(Query query, Class<?> entityClass);

    /**
     * Determine result of given {@link Query} contains at least one element.
     *
     * @param query          the {@link Query} class that specifies the criteria used to find a record.
     * @param entityClass    the parametrized type. Can be {@literal null}.
     * @param collectionName name of the collection to check for objects.
     * @return {@literal true} if the query yields a result.
     */
    boolean exists(Query query, @Nullable Class<?> entityClass, String collectionName);

    /**
     * Map the results of an ad-hoc query on the collection for the entity class to a List of the specified type.
     * <br />
     * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless
     * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
     * <br />
     * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
     * feature rich {@link Query}.
     *
     * @param query       the query class that specifies the criteria used to find a record and also an optional fields
     *                    specification. Must not be {@literal null}.
     * @param entityClass the parametrized type of the returned list. Must not be {@literal null}.
     * @return the List of converted objects.
     */
    <T> List<T> find(Query query, Class<T> entityClass);

    /**
     * Map the results of an ad-hoc query on the specified collection to a List of the specified type.
     * <br />
     * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless
     * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
     * <br />
     * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
     * feature rich {@link Query}.
     *
     * @param query          the query class that specifies the criteria used to find a record and also an optional fields
     *                       specification. Must not be {@literal null}.
     * @param entityClass    the parametrized type of the returned list. Must not be {@literal null}.
     * @param collectionName name of the collection to retrieve the objects from. Must not be {@literal null}.
     * @return the List of converted objects.
     */
    <T> List<T> find(Query query, Class<T> entityClass, String collectionName);

    /**
     * Returns a document with the given id mapped onto the given class. The collection the query is ran against will be
     * derived from the given target class as well.
     *
     * @param id          the id of the document to return. Must not be {@literal null}.
     * @param entityClass the type the document shall be converted into. Must not be {@literal null}.
     * @return the document with the given id mapped onto the given target class.
     */
    @Nullable
    <T> T findById(Object id, Class<T> entityClass);

    /**
     * Returns the document with the given id from the given collection mapped onto the given target class.
     *
     * @param id             the id of the document to return.
     * @param entityClass    the type to convert the document to.
     * @param collectionName the collection to query for the document.
     * @return he converted object or {@literal null} if document does not exist.
     */
    @Nullable
    <T> T findById(Object id, Class<T> entityClass, String collectionName);

    /**
     * Finds the distinct values for a specified {@literal field} across a single {@link MongoCollection} or view and
     * returns the results in a {@link List}.
     *
     * @param field       the name of the field to inspect for distinct values. Must not be {@literal null}.
     * @param entityClass the domain type used for determining the actual {@link MongoCollection}. Must not be
     *                    {@literal null}.
     * @param resultClass the result type. Must not be {@literal null}.
     * @return never {@literal null}.
     * @since 2.1
     */
    default <T> List<T> findDistinct(String field, Class<?> entityClass, Class<T> resultClass) {
        return findDistinct(new Query(), field, entityClass, resultClass);
    }

    /**
     * Finds the distinct values for a specified {@literal field} across a single {@link MongoCollection} or view and
     * returns the results in a {@link List}.
     *
     * @param query       filter {@link Query} to restrict search. Must not be {@literal null}.
     * @param field       the name of the field to inspect for distinct values. Must not be {@literal null}.
     * @param entityClass the domain type used for determining the actual {@link MongoCollection} and mapping the
     *                    {@link Query} to the domain type fields. Must not be {@literal null}.
     * @param resultClass the result type. Must not be {@literal null}.
     * @return never {@literal null}.
     * @since 2.1
     */
    <T> List<T> findDistinct(Query query, String field, Class<?> entityClass, Class<T> resultClass);

    /**
     * Finds the distinct values for a specified {@literal field} across a single {@link MongoCollection} or view and
     * returns the results in a {@link List}.
     *
     * @param query          filter {@link Query} to restrict search. Must not be {@literal null}.
     * @param field          the name of the field to inspect for distinct values. Must not be {@literal null}.
     * @param collectionName the explicit name of the actual {@link MongoCollection}. Must not be {@literal null}.
     * @param entityClass    the domain type used for mapping the {@link Query} to the domain type fields.
     * @param resultClass    the result type. Must not be {@literal null}.
     * @return never {@literal null}.
     * @since 2.1
     */
    <T> List<T> findDistinct(Query query, String field, String collectionName, Class<?> entityClass,
                             Class<T> resultClass);

    /**
     * Finds the distinct values for a specified {@literal field} across a single {@link MongoCollection} or view and
     * returns the results in a {@link List}.
     *
     * @param query       filter {@link Query} to restrict search. Must not be {@literal null}.
     * @param field       the name of the field to inspect for distinct values. Must not be {@literal null}.
     * @param collection  the explicit name of the actual {@link MongoCollection}. Must not be {@literal null}.
     * @param resultClass the result type. Must not be {@literal null}.
     * @return never {@literal null}.
     * @since 2.1
     */
    default <T> List<T> findDistinct(Query query, String field, String collection, Class<T> resultClass) {
        return findDistinct(query, field, collection, Object.class, resultClass);
    }

    /**
     * Returns the number of documents for the given {@link Query} by querying the collection of the given entity class.
     * <br />
     * <strong>NOTE:</strong> Query {@link Query#getSkip() offset} and {@link Query#getLimit() limit} can have direct
     * influence on the resulting number of documents found as those values are passed on to the server and potentially
     * limit the range and order within which the server performs the count operation. Use an {@literal unpaged} query to
     * count all matches.
     * <br />
     * This method uses an
     * {@link com.mongodb.client.MongoCollection#countDocuments(org.bson.conversions.Bson, com.mongodb.client.model.CountOptions)
     * aggregation execution} even for empty {@link Query queries} which may have an impact on performance, but guarantees
     * shard, session and transaction compliance. In case an inaccurate count satisfies the applications needs use
     * {@link MongoOperations#estimatedCount(Class)} for empty queries instead.
     *
     * @param query       the {@link Query} class that specifies the criteria used to find documents. Must not be
     *                    {@literal null}.
     * @param entityClass class that determines the collection to use. Must not be {@literal null}.
     * @return the count of matching documents.
     * @throws org.springframework.data.mapping.MappingException if the collection name cannot be
     *                                                           {@link org.springframework.data.mongodb.core.MongoOperations#getCollectionName(java.lang.Class)} from the given type.
     */
    long count(Query query, Class<?> entityClass);

    /**
     * Returns the number of documents for the given {@link Query} querying the given collection. The given {@link Query}
     * must solely consist of document field references as we lack type information to map potential property references
     * onto document fields. Use {@link MongoOperations#count(Query, Class, String)} to get full type specific support. <br />
     * <strong>NOTE:</strong> Query {@link Query#getSkip() offset} and {@link Query#getLimit() limit} can have direct
     * influence on the resulting number of documents found as those values are passed on to the server and potentially
     * limit the range and order within which the server performs the count operation. Use an {@literal unpaged} query to
     * count all matches.
     * <br />
     * This method uses an
     * {@link com.mongodb.client.MongoCollection#countDocuments(org.bson.conversions.Bson, com.mongodb.client.model.CountOptions)
     * aggregation execution} even for empty {@link Query queries} which may have an impact on performance, but guarantees
     * shard, session and transaction compliance. In case an inaccurate count satisfies the applications needs use
     * {@link MongoOperations#estimatedCount(String)} for empty queries instead.
     *
     * @param query          the {@link Query} class that specifies the criteria used to find documents.
     * @param collectionName must not be {@literal null} or empty.
     * @return the count of matching documents.
     * @see MongoOperations#count(Query, Class, String)
     */
    long count(Query query, String collectionName);

    /**
     * 更新插入
     * Performs an upsert. If no document is found that matches the query, a new document is created and inserted by
     * combining the query document and the update document. <br />
     * <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
     * Use {@link MongoOperations#findAndModify(Query, UpdateDefinition, FindAndModifyOptions, Class, String)} instead.
     *
     * @param query       the query document that specifies the criteria used to select a record to be upserted. Must not be
     *                    {@literal null}.
     * @param update      the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                    the existing object. Must not be {@literal null}.
     * @param entityClass class that determines the collection to use. Must not be {@literal null}.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link MongoOperations#getCollectionName(Class) derived} from the given type.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult upsert(Query query, UpdateDefinition update, Class<?> entityClass);

    /**
     * 更新插入
     * Performs an upsert. If no document is found that matches the query, a new document is created and inserted by
     * combining the query document and the update document. <br />
     * <strong>NOTE:</strong> Any additional support for field mapping, versions, etc. is not available due to the lack of
     * domain type information. Use {@link #upsert(Query, UpdateDefinition, Class, String)} to get full type specific
     * support. <br />
     * <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
     * Use {@link MongoOperations#findAndModify(Query, UpdateDefinition, FindAndModifyOptions, Class, String)} instead.
     *
     * @param query          the query document that specifies the criteria used to select a record to be upserted. Must not be
     *                       {@literal null}.
     * @param update         the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                       the existing object. Must not be {@literal null}.
     * @param collectionName name of the collection to update the object in.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult upsert(Query query, UpdateDefinition update, String collectionName);

    /**
     * 更新插入
     * Performs an upsert. If no document is found that matches the query, a new document is created and inserted by
     * combining the query document and the update document.
     *
     * @param query          the query document that specifies the criteria used to select a record to be upserted. Must not be
     *                       {@literal null}.
     * @param update         the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                       the existing object. Must not be {@literal null}.
     * @param entityClass    class of the pojo to be operated on. Must not be {@literal null}.
     * @param collectionName name of the collection to update the object in. Must not be {@literal null}.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult upsert(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName);

    /**
     * Updates the first object that is found in the collection of the entity class that matches the query document with
     * the provided update document.
     *
     * @param query       the query document that specifies the criteria used to select a record to be updated. Must not be
     *                    {@literal null}.
     * @param update      the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                    the existing. Must not be {@literal null}.
     * @param entityClass class that determines the collection to use.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link MongoOperations#getCollectionName(Class) derived} from the given type.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult updateFirst(Query query, UpdateDefinition update, Class<?> entityClass);

    /**
     * Updates the first object that is found in the specified collection that matches the query document criteria with
     * the provided updated document. <br />
     * <strong>NOTE:</strong> Any additional support for field mapping, versions, etc. is not available due to the lack of
     * domain type information. Use {@link #updateFirst(Query, UpdateDefinition, Class, String)} to get full type specific
     * support. <br />
     * <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
     * Use {@link MongoOperations#findAndModify(Query, UpdateDefinition, Class, String)} instead.
     *
     * @param query          the query document that specifies the criteria used to select a record to be updated. Must not be
     *                       {@literal null}.
     * @param update         the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                       the existing. Must not be {@literal null}.
     * @param collectionName name of the collection to update the object in. Must not be {@literal null}.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult updateFirst(Query query, UpdateDefinition update, String collectionName);

    /**
     * Updates the first object that is found in the specified collection that matches the query document criteria with
     * the provided updated document. <br />
     *
     * @param query          the query document that specifies the criteria used to select a record to be updated. Must not be
     *                       {@literal null}.
     * @param update         the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                       the existing. Must not be {@literal null}.
     * @param entityClass    class of the pojo to be operated on. Must not be {@literal null}.
     * @param collectionName name of the collection to update the object in. Must not be {@literal null}.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult updateFirst(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName);

    /**
     * Updates all objects that are found in the collection for the entity class that matches the query document criteria
     * with the provided updated document.
     *
     * @param query       the query document that specifies the criteria used to select a record to be updated. Must not be
     *                    {@literal null}.
     * @param update      the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                    the existing. Must not be {@literal null}.
     * @param entityClass class of the pojo to be operated on. Must not be {@literal null}.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link MongoOperations#getCollectionName(Class) derived} from the given type.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult updateMulti(Query query, UpdateDefinition update, Class<?> entityClass);

    /**
     * Updates all objects that are found in the specified collection that matches the query document criteria with the
     * provided updated document. <br />
     * <strong>NOTE:</strong> Any additional support for field mapping, versions, etc. is not available due to the lack of
     * domain type information. Use {@link #updateMulti(Query, UpdateDefinition, Class, String)} to get full type specific
     * support.
     *
     * @param query          the query document that specifies the criteria used to select a record to be updated. Must not be
     *                       {@literal null}.
     * @param update         the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                       the existing. Must not be {@literal null}.
     * @param collectionName name of the collection to update the object in. Must not be {@literal null}.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult updateMulti(Query query, UpdateDefinition update, String collectionName);

    /**
     * Updates all objects that are found in the collection for the entity class that matches the query document criteria
     * with the provided updated document.
     *
     * @param query          the query document that specifies the criteria used to select a record to be updated. Must not be
     *                       {@literal null}.
     * @param update         the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                       the existing. Must not be {@literal null}.
     * @param entityClass    class of the pojo to be operated on. Must not be {@literal null}.
     * @param collectionName name of the collection to update the object in. Must not be {@literal null}.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult updateMulti(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName);

    /**
     * Remove the given object from the collection by {@literal id} and (if applicable) its
     * {@link org.springframework.data.annotation.Version}. <br />
     * Use {@link DeleteResult#getDeletedCount()} for insight whether an {@link DeleteResult#wasAcknowledged()
     * acknowledged} remove operation was successful or not.
     *
     * @param object must not be {@literal null}.
     * @return the {@link DeleteResult} which lets you access the results of the previous delete.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link MongoOperations#getCollectionName(Class) derived} from the given object type.
     */
    DeleteResult remove(Object object);

    /**
     * Removes the given object from the given collection by {@literal id} and (if applicable) its
     * {@link org.springframework.data.annotation.Version}. <br />
     * Use {@link DeleteResult#getDeletedCount()} for insight whether an {@link DeleteResult#wasAcknowledged()
     * acknowledged} remove operation was successful or not.
     *
     * @param object         must not be {@literal null}.
     * @param collectionName name of the collection where the objects will removed, must not be {@literal null} or empty.
     * @return the {@link DeleteResult} which lets you access the results of the previous delete.
     */
    DeleteResult remove(Object object, String collectionName);

    /**
     * Remove all documents that match the provided query document criteria from the the collection used to store the
     * entityClass. The Class parameter is also used to help convert the Id of the object if it is present in the query.
     *
     * @param query       the query document that specifies the criteria used to remove a record.
     * @param entityClass class that determines the collection to use.
     * @return the {@link DeleteResult} which lets you access the results of the previous delete.
     * @throws IllegalArgumentException                          when {@literal query} or {@literal entityClass} is {@literal null}.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link MongoOperations#getCollectionName(Class) derived} from the given type.
     */
    DeleteResult remove(Query query, Class<?> entityClass);

    /**
     * Remove all documents that match the provided query document criteria from the the collection used to store the
     * entityClass. The Class parameter is also used to help convert the Id of the object if it is present in the query.
     *
     * @param query          the query document that specifies the criteria used to remove a record.
     * @param entityClass    class of the pojo to be operated on. Can be {@literal null}.
     * @param collectionName name of the collection where the objects will removed, must not be {@literal null} or empty.
     * @return the {@link DeleteResult} which lets you access the results of the previous delete.
     * @throws IllegalArgumentException when {@literal query}, {@literal entityClass} or {@literal collectionName} is
     *                                  {@literal null}.
     */
    DeleteResult remove(Query query, Class<?> entityClass, String collectionName);

    /**
     * Remove all documents from the specified collection that match the provided query document criteria. There is no
     * conversion/mapping done for any criteria using the id field. <br />
     * <strong>NOTE:</strong> Any additional support for field mapping is not available due to the lack of domain type
     * information. Use {@link #remove(Query, Class, String)} to get full type specific support.
     *
     * @param query          the query document that specifies the criteria used to remove a record.
     * @param collectionName name of the collection where the objects will removed, must not be {@literal null} or empty.
     * @return the {@link DeleteResult} which lets you access the results of the previous delete.
     * @throws IllegalArgumentException when {@literal query} or {@literal collectionName} is {@literal null}.
     */
    DeleteResult remove(Query query, String collectionName);

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358
  • 359
  • 360
  • 361
  • 362
  • 363
  • 364
  • 365
  • 366
  • 367
  • 368
  • 369
  • 370
  • 371
  • 372
  • 373
  • 374
  • 375
  • 376
  • 377
  • 378
  • 379
  • 380
  • 381
  • 382
  • 383
  • 384
  • 385
  • 386
  • 387
  • 388
  • 389
  • 390
  • 391
  • 392
  • 393
  • 394
  • 395
  • 396
  • 397
  • 398
  • 399
  • 400
  • 401
  • 402
  • 403
  • 404
  • 405
  • 406
  • 407
  • 408
  • 409
  • 410
  • 411
  • 412
  • 413
  • 414
  • 415
  • 416
  • 417
  • 418
  • 419
  • 420
  • 421
  • 422
  • 423
  • 424
  • 425
  • 426
  • 427
  • 428
  • 429
  • 430
  • 431
  • 432
  • 433
  • 434
  • 435
  • 436
  • 437
  • 438
  • 439
  • 440
  • 441
  • 442
  • 443
  • 444
  • 445
  • 446
  • 447
  • 448
  • 449
  • 450
  • 451
  • 452
  • 453
  • 454
  • 455
  • 456
  • 457
  • 458
  • 459
  • 460
  • 461
  • 462
  • 463
  • 464
  • 465
  • 466
  • 467
  • 468
  • 469
  • 470
  • 471
  • 472
  • 473
  • 474
  • 475
  • 476
  • 477
  • 478
  • 479
  • 480
  • 481
  • 482
  • 483
  • 484
  • 485
  • 486
  • 487
  • 488
  • 489
  • 490
  • 491
  • 492
  • 493
  • 494
  • 495
  • 496
  • 497
  • 498
  • 499
  • 500
  • 501
  • 502
  • 503
  • 504
  • 505
  • 506
  • 507
  • 508
  • 509
  • 510
  • 511
  • 512
  • 513
  • 514
  • 515
  • 516
  • 517
  • 518
  • 519
  • 520
  • 521
  • 522
  • 523
  • 524
  • 525
  • 526
  • 527
  • 528
  • 529
  • 530
  • 531
  • 532
  • 533
  • 534
  • 535
  • 536
  • 537
  • 538
  • 539
  • 540
  • 541
  • 542
  • 543
  • 544
  • 545
  • 546
  • 547
  • 548
  • 549
  • 550
  • 551
  • 552
  • 553
  • 554
  • 555
  • 556
  • 557
  • 558
  • 559
  • 560
  • 561
  • 562
  • 563
  • 564
  • 565
  • 566
  • 567
  • 568
  • 569
  • 570
  • 571
  • 572
  • 573
  • 574
  • 575
  • 576
  • 577
  • 578
  • 579
  • 580
  • 581
  • 582
  • 583
  • 584
  • 585
  • 586
  • 587
  • 588
  • 589
  • 590
  • 591
  • 592
  • 593
  • 594
  • 595
  • 596
  • 597
  • 598
  • 599
  • 600
  • 601
  • 602
  • 603
  • 604
  • 605
  • 606
  • 607
  • 608
  • 609
  • 610
  • 611
  • 612
  • 613
  • 614
  • 615
  • 616
  • 617
  • 618
  • 619
  • 620
  • 621
  • 622
  • 623
  • 624
  • 625
  • 626
  • 627
  • 628
  • 629
  • 630
  • 631
  • 632
  • 633
  • 634
  • 635
  • 636
  • 637
  • 638
  • 639
  • 640
  • 641
  • 642
  • 643
  • 644
  • 645
  • 646
  • 647
  • 648
  • 649
  • 650
  • 651
  • 652
  • 653
  • 654
  • 655
  • 656
  • 657
  • 658
  • 659
  • 660
  • 661
  • 662
  • 663
  • 664
  • 665
  • 666
  • 667

实现类

@Repository
public class MongoRepositoryImpl implements MongoRepository {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public MongoOperations getMongoTemplate() {
        return mongoTemplate;
    }

    @Override
    public MongoCollection<Document> getCollection(String collectionName) {
        return mongoTemplate.getCollection(collectionName);
    }

    @Override
    public MongoCollection<Document> getCollection(Query query, String collectionName) {
        mongoTemplate.count(query, collectionName);
        return mongoTemplate.getCollection(collectionName);
    }

    @Override
    public void insert(String collectionName, Document doc) {
        MongoCollection<Document> collection = getCollection(collectionName);
        collection.insertOne(doc);
    }

    @Override
    public long count(String collectionName, Bson filter) {
        MongoCollection<Document> collection = getCollection(collectionName);
        return collection.countDocuments(filter);
    }

    @Override
    public long countByLimit(String collectionName, Integer limit, Bson filter) {
        MongoCollection<Document> collection = getCollection(collectionName);
        CountOptions countOptions = new CountOptions();
        countOptions.limit(limit);
        return collection.countDocuments(filter, countOptions);
    }

    @Override
    public long distinctCount(String collectionName, Bson filter, String fieldName) {
        MongoCollection<Document> collection = getCollection(collectionName);
        long count = 0;
        if (StringUtils.isEmpty(fieldName)) {
            return 0L;
        }
        for (BsonValue ignored : collection.distinct(fieldName, filter, BsonValue.class)) {
            count++;
        }
        return count;
    }

    @Override
    public AggregateIterable<Document> aggregate(String collectionName, List<Bson> pipeline) {
        MongoCollection<Document> collection = getCollection(collectionName);
        return collection.aggregate(pipeline);
    }

    @Override
    public FindIterable<Document> find(String collectionName, Bson filter) {
        MongoCollection<Document> collection = getCollection(collectionName);
        return collection.find(filter);
    }

    @Override
    public long update(String collectionName, Bson filter, Document updateDoc) {
        MongoCollection<Document> collection = getCollection(collectionName);
        return collection.updateOne(filter, updateDoc).getModifiedCount();
    }

    @Override
    public String getCollectionName(Class<?> entityClass) {
        return mongoTemplate.getCollectionName(entityClass);
    }

    @Override
    public <T> T insert(T objectToSave) {
        return mongoTemplate.insert(objectToSave);
    }

    @Override
    public <T> T insert(T objectToSave, String collectionName) {
        return mongoTemplate.insert(objectToSave, collectionName);
    }

    @Override
    public <T> Collection<T> insert(Collection<? extends T> batchToSave, Class<?> entityClass) {
        return mongoTemplate.insert(batchToSave, entityClass);
    }

    @Override
    public <T> Collection<T> insert(Collection<? extends T> batchToSave, String collectionName) {
        return mongoTemplate.insert(batchToSave, collectionName);
    }

    @Override
    public <T> Collection<T> insertAll(Collection<? extends T> objectsToSave) {
        return mongoTemplate.insertAll(objectsToSave);
    }

    @Override
    public <T> T save(T objectToSave) {
        return mongoTemplate.save(objectToSave);
    }

    @Override
    public <T> T save(T objectToSave, String collectionName) {
        return mongoTemplate.save(objectToSave, collectionName);
    }

    @Override
    public <T> T findOne(Query query, Class<T> entityClass) {
        return mongoTemplate.findOne(query, entityClass);
    }

    @Override
    public <T> T findOne(Query query, Class<T> entityClass, String collectionName) {
        return mongoTemplate.findOne(query, entityClass, collectionName);
    }

    @Override
    public boolean exists(Query query, String collectionName) {
        return mongoTemplate.exists(query, collectionName);
    }

    @Override
    public boolean exists(Query query, Class<?> entityClass) {
        return mongoTemplate.exists(query, entityClass);
    }

    @Override
    public boolean exists(Query query, Class<?> entityClass, String collectionName) {
        return mongoTemplate.exists(query, entityClass);
    }

    @Override
    public <T> List<T> find(Query query, Class<T> entityClass) {
        return mongoTemplate.find(query, entityClass);
    }

    @Override
    public <T> List<T> find(Query query, Class<T> entityClass, String collectionName) {
        return mongoTemplate.find(query, entityClass, collectionName);
    }

    @Override
    public <T> T findById(Object id, Class<T> entityClass) {
        return mongoTemplate.findById(id, entityClass);
    }

    @Override
    public <T> T findById(Object id, Class<T> entityClass, String collectionName) {
        return mongoTemplate.findById(id, entityClass, collectionName);
    }

    @Override
    public <T> List<T> findDistinct(String field, Class<?> entityClass, Class<T> resultClass) {
        return mongoTemplate.findDistinct(field, entityClass, resultClass);
    }

    @Override
    public <T> List<T> findDistinct(Query query, String field, Class<?> entityClass, Class<T> resultClass) {
        return mongoTemplate.findDistinct(query, field, entityClass, resultClass);
    }

    @Override
    public <T> List<T> findDistinct(Query query, String field, String collectionName, Class<?> entityClass, Class<T> resultClass) {
        return mongoTemplate.findDistinct(query, field, collectionName, entityClass, resultClass);
    }

    @Override
    public <T> List<T> findDistinct(Query query, String field, String collection, Class<T> resultClass) {
        return mongoTemplate.findDistinct(query, field, collection, resultClass);
    }

    @Override
    public long count(Query query, Class<?> entityClass) {
        return mongoTemplate.count(query, entityClass);
    }

    @Override
    public long count(Query query, String collectionName) {
        return mongoTemplate.count(query, collectionName);
    }

    @Override
    public UpdateResult upsert(Query query, UpdateDefinition update, Class<?> entityClass) {
        return mongoTemplate.upsert(query, update, entityClass);
    }

    @Override
    public UpdateResult upsert(Query query, UpdateDefinition update, String collectionName) {
        return mongoTemplate.upsert(query, update, collectionName);
    }

    @Override
    public UpdateResult upsert(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName) {
        return mongoTemplate.upsert(query, update, entityClass, collectionName);
    }

    @Override
    public UpdateResult updateFirst(Query query, UpdateDefinition update, Class<?> entityClass) {
        return mongoTemplate.updateFirst(query, update, entityClass);
    }

    @Override
    public UpdateResult updateFirst(Query query, UpdateDefinition update, String collectionName) {
        return mongoTemplate.updateFirst(query, update, collectionName);
    }

    @Override
    public UpdateResult updateFirst(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName) {
        return mongoTemplate.updateFirst(query, update, entityClass, collectionName);
    }

    @Override
    public UpdateResult updateMulti(Query query, UpdateDefinition update, Class<?> entityClass) {
        return mongoTemplate.updateMulti(query, update, entityClass);
    }

    @Override
    public UpdateResult updateMulti(Query query, UpdateDefinition update, String collectionName) {
        return mongoTemplate.updateMulti(query, update, collectionName);
    }

    @Override
    public UpdateResult updateMulti(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName) {
        return mongoTemplate.updateMulti(query, update, entityClass, collectionName);
    }

    @Override
    public DeleteResult remove(Object object) {
        return mongoTemplate.remove(object);
    }

    @Override
    public DeleteResult remove(Object object, String collectionName) {
        return mongoTemplate.remove(object, collectionName);
    }

    @Override
    public DeleteResult remove(Query query, Class<?> entityClass) {
        return mongoTemplate.remove(query, entityClass);
    }

    @Override
    public DeleteResult remove(Query query, Class<?> entityClass, String collectionName) {
        return mongoTemplate.remove(query, entityClass, collectionName);
    }

    @Override
    public DeleteResult remove(Query query, String collectionName) {
        return mongoTemplate.remove(query, collectionName);
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259

后续直接使用仓库类即可
测试类

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class ProcessTest {

    @Autowired
    private MongoRepository mongoRepository;

    @Test
    public void test() {
        String collectionName = mongoGateway.getCollectionName(User.class);
        System.out.println(collectionName);
        User user = new User();
        user.setId(1L);
        user.setUser_id(1111L);
        user.setAge(10);
        User user1 = mongoRepository.save(user, "user");
        System.out.println("新增user: " + JSON.toJSONString(user1));

        Query query = new Query();
        Criteria criteria = new Criteria(TableInfoEnum.USER.getUniqueFieldName());
        criteria.is(user.getUser_id());
        query.addCriteria(criteria);

        user.setAge(18);
        Update update = new Update();
        setUpdate(update, user);
        mongoRepository.updateMulti(query, update, User.class, "user");

        User one = mongoRepository.findOne(query, User.class, "user");
        System.out.println("one: " + JSON.toJSONString(one));
    }

    public void setUpdate(Update update, Object object) {
        if (null == object) {
            return;
        }
        Class<?> clazz = object.getClass();

        BeanInfo beanInfo;
        try {
            beanInfo = Introspector.getBeanInfo(clazz);

            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                String name = propertyDescriptor.getName();
                if (!"class".equalsIgnoreCase(name)) {
                    Method readMethod = propertyDescriptor.getReadMethod();
                    readMethod.setAccessible(true);
                    Object invoke = readMethod.invoke(object, null);
                    if (null != invoke) {
                        update.set(name, invoke);
                        System.out.println("name: " + name + " invoke: " + invoke);
                    }
                }

            }
        } catch (IntrospectionException | InvocationTargetException | IllegalAccessException e) {
            log.error("setUpdate属性失败,错误日志: {[]}", e);
        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63

官方文档参考: https://docs.spring.io/spring-data/mongodb/reference/mongodb.html

the end !!!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/698860
推荐阅读
相关标签
  

闽ICP备14008679号