spring data mongodb学习以及为repository提供可扩展的自定义方法

来源:http://blog.csdn.net/victor_cindy1/article/details/52151891


Spring Data 概述

Spring Data : Spring 的一个子项目。用于简化数据库访问,支持NoSQL 和 关系数据存储。其主要目标是使数据库的访问变得方便快捷。
SpringData 项目所支持 NoSQL 存储:
MongoDB (文档数据库)
Neo4j(图形数据库)
Redis(键/值存储)
Hbase(列族数据库)
SpringData 项目所支持的关系数据存储技术:
JDBC
JPA

Spring Data mongodb 概述

Spring Data mongodb  : 致力于减少数据访问层 (DAO) 的开发量. 开发者唯一要做的,就只是声明持久层的接口,其他都交给 Spring Data mongodb 来帮你完成!
框架怎么可能代替开发者实现业务逻辑呢?比如:当有一个 customerRepository.findByNameAndAddressNumberAndAccountsAccountName(name, number,accountName)  这样一个方法声明,大致应该能判断出这是根据给定条件 查询出满足条件的 User  对象。Spring Data mongodb 做的便是规范方法的名字,根据符合规范的名字来确定方法需要实现什么样的逻辑。

使用 Spring Data JPA 进行持久层开发需要的四个步骤:

1、配置 Spring 整合 Mongodb

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.dhb.springmvc.config;  
  2.   
  3. import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;  
  4.   
  5. /** 
  6.  * Created by ${denghb} on 2016/7/31. 
  7.  */  
  8. public class DhbWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {  
  9.     @Override  
  10.     protected Class<?>[] getRootConfigClasses() {  
  11.         return new Class<?>[] { RootConfig.class };  
  12.     }  
  13.   
  14.     @Override  
  15.     protected Class<?>[] getServletConfigClasses() {  
  16.         // return new Class<?>[0];  
  17.         return new Class [] { WebConfig.class, C3P0DataSourceBuilder.class, MongodbConfig.class };  
  18.     }  
  19.   
  20.     @Override  
  21.     protected String[] getServletMappings() {  
  22.         return new String[] { "/" };  
  23.     }  
  24. }  

2、让 Spring 为声明的接口创建代理对象。Spring 初始化容器时将会扫描 base-package  指定的包目录及其子目录,为继承 Repository 或其子接口的接口创建代理对象,并将代理对象注册为 Spring Bean,业务层便可以通过 Spring 自动封装的特性来直接使用该对象。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.dhb.springmvc.config;  
  2.   
  3. import com.dhb.springmvc.base.support.CustomMongoRepositoryFactoryBean;  
  4. import com.mongodb.Mongo;  
  5. import com.mongodb.MongoClient;  
  6. import org.springframework.data.mongodb.config.AbstractMongoConfiguration;  
  7. import org.springframework.data.mongodb.config.EnableMongoAuditing;  
  8. import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;  
  9.   
  10. /** 
  11.  * Created by ${denghb} on 2016/8/5. 
  12.  */  
  13. @EnableMongoRepositories(  
  14.         basePackages = {"com.dhb.springmvc"},  
  15.         repositoryFactoryBeanClass = CustomMongoRepositoryFactoryBean.class  
  16. )  
  17. @EnableMongoAuditing  
  18. public class MongodbConfig extends AbstractMongoConfiguration {  
  19.     @Override  
  20.     protected String getDatabaseName() {  
  21.         return "business";  
  22.     }  
  23.   
  24.     @Override  
  25.     public Mongo mongo() throws Exception {  
  26.         return new MongoClient("127.0.0.1");  
  27.     }  
  28. }  
在这里没有配置MongoTemplate,但是在后续的repository里面我们却可以注入进来,原因是继承了AbstractMongoConfiguration ,该抽象类对其进行了实现。

MongoTemplate是数据库和代码之间的接口,对数据库的操作都在它里面。
注:MongoTemplate是线程安全的。
MongoTemplate实现了interface MongoOperations。

MongoDB documents和domain classes之间的映射关系是通过实现了MongoConverter这个interface的类来实现的。
MongoTemplate提供了非常多的操作MongoDB的方法。 它是线程安全的,可以在多线程的情况下使用。
MongoTemplate实现了MongoOperations接口, 此接口定义了众多的操作方法如"find", "findAndModify", "findOne", "insert", "remove", "save", "update" and "updateMulti"等。
它转换domain object为DBObject,并提供了Query, Criteria, and Update等流式API。
缺省转换类为MongoMappingConverter。
3、声明持久层的接口,该接口继承  Repository
Repository 是一个标记型接口,它不包含任何方法,如必要,Spring Data 可实现 Repository 其他子接口,其中定义了一些常用的增删改查,以及分页相关的方法。
在接口中声明需要的方法

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.dhb.springmvc.base.repository;  
  2.   
  3. import com.dhb.springmvc.base.entity.BaseEntity;  
  4. import org.springframework.data.mongodb.repository.MongoRepository;  
  5. import org.springframework.data.repository.NoRepositoryBean;  
  6.   
  7. import java.io.Serializable;  
  8.   
  9. /** 
  10.  * Created by ${denghb} on 2016/8/5. 
  11.  */  
  12. @NoRepositoryBean  
  13. public interface BaseRepository<T extends BaseEntity, ID extends Serializable>  
  14.         extends MongoRepository<T, ID>, BaseRepositoryEnhance<T, ID> {  
  15. }  

下面是可扩张的repository

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.dhb.springmvc.base.repository;  
  2.   
  3. import com.dhb.springmvc.base.entity.BaseEntity;  
  4.   
  5. import java.io.Serializable;  
  6.   
  7. /** 
  8.  * Created by ${denghb} on 2016/8/5. 
  9.  */  
  10. public interface BaseRepositoryEnhance<T extends BaseEntity, ID extends Serializable> {  
  11.   
  12.     T softDelete(ID id);  
  13. }  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.dhb.springmvc.base.repository.impl;  
  2.   
  3. import com.dhb.springmvc.base.entity.BaseEntity;  
  4. import com.dhb.springmvc.base.repository.BaseRepositoryEnhance;  
  5. import org.springframework.data.mongodb.core.MongoOperations;  
  6. import org.springframework.data.mongodb.repository.query.MongoEntityInformation;  
  7. import org.springframework.data.mongodb.repository.support.SimpleMongoRepository;  
  8.   
  9. import java.io.Serializable;  
  10.   
  11. /** 
  12.  * Created by ${denghb} on 2016/8/5. 
  13.  */  
  14. public class BaseRepositoryImpl<T extends BaseEntity, ID extends Serializable>  
  15.         extends SimpleMongoRepository<T, ID>  
  16.         implements BaseRepositoryEnhance<T, ID> {  
  17.   
  18.     private final MongoOperations mongoOperations;  
  19.   
  20.     public BaseRepositoryImpl(MongoEntityInformation<T, ID> metadata, MongoOperations mongoOperations) {  
  21.         super(metadata, mongoOperations);  
  22.         this.mongoOperations = mongoOperations;  
  23.     }  
  24.   
  25.     @Override  
  26.     public T softDelete(ID id) {  
  27.         return null;  
  28.     }  
  29. }  

public BaseRepositoryImpl(MongoEntityInformation<T, ID> metadata, MongoOperations mongoOperations) {
        super(metadata, mongoOperations);
        this.mongoOperations = mongoOperations;
    }

这段代码必须实现,因为父类有一个有参的构造方法,没有无参的构造方法。


父类没有无参构造函数时,子类继承时,构造函数中必须显式调用父类构造方法,并且传递对应所需要的参数。 一个类如果显式的定义了带参构造函数,那么默认无参构造函数自动失效 。

4、Spring Data 将根据给定的策略(具体策略稍后讲解)来为其生成实现代码。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.dhb.springmvc.base.support;  
  2.   
  3. import com.dhb.springmvc.base.entity.BaseEntity;  
  4. import com.dhb.springmvc.base.repository.impl.BaseRepositoryImpl;  
  5. import org.springframework.data.mongodb.core.MongoOperations;  
  6. import org.springframework.data.mongodb.repository.MongoRepository;  
  7. import org.springframework.data.mongodb.repository.query.MongoEntityInformation;  
  8. import org.springframework.data.mongodb.repository.support.MongoRepositoryFactory;  
  9. import org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean;  
  10. import org.springframework.data.mongodb.repository.support.QueryDslMongoRepository;  
  11. import org.springframework.data.querydsl.QueryDslPredicateExecutor;  
  12. import org.springframework.data.repository.core.RepositoryMetadata;  
  13. import org.springframework.data.repository.core.support.RepositoryFactorySupport;  
  14.   
  15. import java.io.Serializable;  
  16.   
  17. import static org.springframework.data.querydsl.QueryDslUtils.QUERY_DSL_PRESENT;  
  18.   
  19. /** 
  20.  * 用于生成自扩展的Repository方法,比如softDelete 
  21.  * Created by ${denghb} on 2016/8/5. 
  22.  */  
  23. public class CustomMongoRepositoryFactoryBean<T extends MongoRepository<S, ID>, S extends BaseEntity, ID extends Serializable>  
  24.         extends MongoRepositoryFactoryBean<T, S, ID> {  
  25.   
  26.     @Override  
  27.     protected RepositoryFactorySupport getFactoryInstance(MongoOperations operations) {  
  28.         return new LCRRepositoryFactory(operations);  
  29.     }  
  30.   
  31.     private static class LCRRepositoryFactory<S extends BaseEntity, ID extends Serializable> extends MongoRepositoryFactory {  
  32.         private final MongoOperations mongoOperations;  
  33.   
  34.         public LCRRepositoryFactory(MongoOperations mongoOperations) {  
  35.             super(mongoOperations);  
  36.             this.mongoOperations = mongoOperations;  
  37.         }  
  38.   
  39.         @Override  
  40.         protected Object getTargetRepository(RepositoryMetadata metadata) {  
  41.             Class<?> repositoryInterface = metadata.getRepositoryInterface();  
  42.             MongoEntityInformation<?, Serializable> entityInformation = getEntityInformation(metadata.getDomainType());  
  43.             if (isQueryDslRepository(repositoryInterface)) {  
  44.                 return new QueryDslMongoRepository(entityInformation, mongoOperations);  
  45.             } else {  
  46.                 return new BaseRepositoryImpl<S, ID>((MongoEntityInformation<S, ID>) entityInformation, this.mongoOperations);  
  47.             }  
  48.         }  
  49.   
  50.         private static boolean isQueryDslRepository(Class<?> repositoryInterface) {  
  51.             return QUERY_DSL_PRESENT && QueryDslPredicateExecutor.class.isAssignableFrom(repositoryInterface);  
  52.         }  
  53.   
  54.         @Override  
  55.         protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {  
  56.             return isQueryDslRepository(metadata.getRepositoryInterface()) ? QueryDslMongoRepository.class  
  57.                     : BaseRepositoryImpl.class;  
  58.         }  
  59.     }  
  60. }  

Repository 接口概述
Repository 接口是 Spring Data 的一个核心接口,它不提供任何方法,开发者需要在自己定义的接口中声明需要的方法 
    public interface Repository<T, ID extends Serializable> { } 
Spring Data可以让我们只定义接口,只要遵循 Spring Data的规范,就无需写实现类。  
与继承 Repository 等价的一种方式,就是在持久层接口上使用 @RepositoryDefinition 注解,并为其指定 domainClass 和 idClass 属性。如下两种方式是完全等价的
Repository 的子接口
基础的 Repository 提供了最基本的数据访问功能,其几个子接口则扩展了一些功能。它们的继承关系如下: 
Repository: 仅仅是一个标识,表明任何继承它的均为仓库接口类
CrudRepository: 继承 Repository,实现了一组 CRUD 相关的方法 
PagingAndSortingRepository: 继承 CrudRepository,实现了一组分页排序相关的方法 
MongoRepository: 继承 PagingAndSortingRepository,实现一组 mongodb规范相关的方法 
自定义的 XxxxRepository 需要继承 MongoRepository,这样的 XxxxRepository 接口就具备了通用的数据访问控制层的能力。

entity实体类:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.dhb.springmvc.entity;  
  2.   
  3. import com.dhb.springmvc.base.entity.BaseEntity;  
  4. import com.dhb.springmvc.entity.support.Account;  
  5. import com.dhb.springmvc.entity.support.Address;  
  6. import org.springframework.data.mongodb.core.mapping.Document;  
  7.   
  8. import java.util.List;  
  9.   
  10. /** 
  11.  * Created by ${denghb} on 2016/8/5. 
  12.  */  
  13. @Document  
  14. public class Customer extends BaseEntity {  
  15.     private String name;  
  16.     private List<Account> accounts;  
  17.     private Address address;  
  18.   
  19.     public String getName() {  
  20.         return name;  
  21.     }  
  22.   
  23.     public void setName(String name) {  
  24.         this.name = name;  
  25.     }  
  26.   
  27.     public List<Account> getAccounts() {  
  28.         return accounts;  
  29.     }  
  30.   
  31.     public void setAccounts(List<Account> accounts) {  
  32.         this.accounts = accounts;  
  33.     }  
  34.   
  35.     public Address getAddress() {  
  36.         return address;  
  37.     }  
  38.   
  39.     public void setAddress(Address address) {  
  40.         this.address = address;  
  41.     }  
  42. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.dhb.springmvc.entity.support;  
  2.   
  3. import com.dhb.springmvc.base.entity.BaseEntity;  
  4.   
  5. /** 
  6.  * Created by ${denghb} on 2016/8/5. 
  7.  */  
  8. public class Account extends BaseEntity {  
  9.     private String accountName;  
  10.   
  11.     public String getAccountName() {  
  12.         return accountName;  
  13.     }  
  14.   
  15.     public void setAccountName(String accountName) {  
  16.         this.accountName = accountName;  
  17.     }  
  18. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.dhb.springmvc.entity.support;  
  2.   
  3. import com.dhb.springmvc.base.entity.BaseEntity;  
  4.   
  5. /** 
  6.  * Created by ${denghb} on 2016/8/5. 
  7.  */  
  8. public class Address extends BaseEntity {  
  9.     private String number;  
  10.     private String street;  
  11.     private String town;  
  12.     private String postcode;  
  13.   
  14.     public String getNumber() {  
  15.         return number;  
  16.     }  
  17.   
  18.     public void setNumber(String number) {  
  19.         this.number = number;  
  20.     }  
  21.   
  22.     public String getStreet() {  
  23.         return street;  
  24.     }  
  25.   
  26.     public void setStreet(String street) {  
  27.         this.street = street;  
  28.     }  
  29.   
  30.     public String getTown() {  
  31.         return town;  
  32.     }  
  33.   
  34.     public void setTown(String town) {  
  35.         this.town = town;  
  36.     }  
  37.   
  38.     public String getPostcode() {  
  39.         return postcode;  
  40.     }  
  41.   
  42.     public void setPostcode(String postcode) {  
  43.         this.postcode = postcode;  
  44.     }  
  45. }  

repository类:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.dhb.springmvc.repository;  
  2.   
  3. import com.dhb.springmvc.entity.Customer;  
  4.   
  5. import java.util.List;  
  6.   
  7. /** 
  8.  * Created by ${denghb} on 2016/8/8. 
  9.  */  
  10. public interface CustomerRepositoryEnhance {  
  11.     public List<Customer> search(String keyword, String direction, String sort, int page, int size);  
  12. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.dhb.springmvc.repository.impl;  
  2.   
  3. import com.dhb.springmvc.entity.Customer;  
  4. import com.dhb.springmvc.repository.CustomerRepositoryEnhance;  
  5. import org.springframework.data.domain.PageRequest;  
  6. import org.springframework.data.domain.Sort;  
  7. import org.springframework.data.mongodb.core.MongoTemplate;  
  8. import org.springframework.data.mongodb.core.query.Criteria;  
  9. import org.springframework.data.mongodb.core.query.Query;  
  10.   
  11. import javax.annotation.Resource;  
  12. import java.util.List;  
  13.   
  14. /** 
  15.  * Created by ${denghb} on 2016/8/8. 
  16.  */  
  17. public class CustomerRepositoryImpl implements CustomerRepositoryEnhance {  
  18.   
  19.     @Resource  
  20.     private MongoTemplate mongoTemplate;  
  21.   
  22.     @Override  
  23.     public List<Customer> search(String keyword, String direction, String sort, int page, int size) {  
  24.         Query query = new Query();  
  25.         Criteria c = new Criteria();  
  26.         query.addCriteria(Criteria.where("name").is(keyword));  
  27.         query.with(new Sort(Sort.Direction.valueOf(direction), sort));  
  28.         query.with(new PageRequest(page - 1, size));  
  29.         return mongoTemplate.find(query, Customer.class);  
  30.     }  
  31. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.dhb.springmvc.repository;  
  2.   
  3. import com.dhb.springmvc.base.repository.BaseRepository;  
  4. import com.dhb.springmvc.entity.Customer;  
  5. import org.springframework.stereotype.Repository;  
  6.   
  7. import java.util.List;  
  8.   
  9. /** 
  10.  * Created by ${denghb} on 2016/8/5. 
  11.  */  
  12. @Repository  
  13. public interface CustomerRepository extends BaseRepository<Customer, String>, CustomerRepositoryEnhance {  
  14.   
  15.     List<Customer> findByNameAndAddressNumberAndAccountsAccountName(  
  16.             String name, String number, String accountName);  
  17. }  

service类:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.dhb.springmvc.service;  
  2.   
  3. import com.dhb.springmvc.entity.Customer;  
  4. import com.dhb.springmvc.repository.CustomerRepository;  
  5. import org.springframework.stereotype.Service;  
  6.   
  7. import javax.annotation.Resource;  
  8. import java.util.List;  
  9.   
  10. /** 
  11.  * Created by ${denghb} on 2016/8/5. 
  12.  */  
  13. @Service  
  14. public class CustomerService {  
  15.   
  16.     @Resource  
  17.     private CustomerRepository customerRepository;  
  18.   
  19.     public void insertCustomer(Customer customer) {  
  20.         customerRepository.save(customer);  
  21.     }  
  22.   
  23.     public List<Customer> findAllCustomers() {  
  24.         return customerRepository.findAll();  
  25.     }  
  26.   
  27.     public void dropCustomerCollection() {  
  28.         customerRepository.deleteAll();  
  29.     }  
  30.   
  31.     public List<Customer> findByNameAndAddressNumberAndAccountsAccountName(String name, String number, String accountName) {  
  32.         return customerRepository.findByNameAndAddressNumberAndAccountsAccountName(name, number,accountName);  
  33.     }  
  34.   
  35.     public List<Customer> search(String keyword, String direction, String sort, int page, int size) {  
  36.         return customerRepository.search(keyword, direction, sort, page, size);  
  37.     }  
  38. }  

restController类:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.dhb.springmvc.controller;  
  2.   
  3. import com.dhb.springmvc.entity.Customer;  
  4. import com.dhb.springmvc.service.CustomerService;  
  5. import org.springframework.web.bind.annotation.*;  
  6.   
  7. import javax.annotation.Resource;  
  8. import java.util.List;  
  9.   
  10. /** 
  11.  * Created by ${denghb} on 2016/8/5. 
  12.  */  
  13. @RestController  
  14. @RequestMapping(value = "/v0.1/customer")  
  15. public class CustomerController {  
  16.     @Resource  
  17.     private CustomerService customerService;  
  18.   
  19.     @RequestMapping(value = "/get_all", method = RequestMethod.GET)  
  20.     public Object findAllCustomerDetail() {  
  21.         return customerService.findAllCustomers();  
  22.     }  
  23.   
  24.     @RequestMapping(value = "/get_by/{name}/{number}/{accountName}", method = RequestMethod.GET)  
  25.     public Object findByNameAndAddressNumberAndAccountsAccountName(@PathVariable String name, @PathVariable String number, @PathVariable String accountName) {  
  26.         return customerService.findByNameAndAddressNumberAndAccountsAccountName(name, number, accountName);  
  27.     }  
  28.     @RequestMapping(value = "/search_by", method = RequestMethod.GET)  
  29.     public List<Customer> search(@RequestParam(value= "query", defaultValue = "") String keyword,  
  30.                                  @RequestParam(value= "direction", defaultValue = "DESC") String direction,  
  31.                                  @RequestParam(value = "sort", defaultValue = "name") String sort,  
  32.                                  @RequestParam(value = "page", defaultValue = "1"int page,  
  33.                                  @RequestParam(value = "size", defaultValue = "30"int size) {  
  34.   
  35.         return customerService.search(keyword, direction, sort, page, size);  
  36.     }  
  37. }  


1、为某一个 Repository 上添加自定义方法

1)定义一个接口: 声明要添加的自实现的方法

2)提供该接口的实现类: 类名需在要声明的 Repository 后添加 Impl, 并实现方法

3)声明 Repository 接口, 并继承 1) 声明的接口

注意: 默认情况下, Spring Data 会在 base-package 中查找 "接口名Impl" 作为实现类. 也可以通过 repository-impl-postfix 声明后缀. 


2、为所有的 Repository 都添加自实现的方法

1)声明一个接口, 在该接口中声明需要自定义的方法

2)提供 1) 所声明的接口的实现类. 且继承 SimpleJpaRepository, 并提供方法的实现

3)声明 Repository 接口, 并继承 1) 声明的接口, 且该接口需要继承 Spring Data 的 Repository.

4)定义 MongoRepositoryFactoryBean的实现类, 使其生成 1) 定义的接口实现类的对象

5)修改 mongodb repository节点的 factory-class 属性指向 3) 的全类名

注意: 全局的扩展实现类不要用 Imp 作为后缀名, 或为全局扩展接口添加 @NoRepositoryBean 注解告知  Spring Data: Spring Data 不把其作为 Repository

项目工程目录如下(部分配置适用于别的测试,可以无视):




  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Data MongoDB 中,可以使用 Aggregation Framework 来进行多表分组。下面是一个示例: 假设我们有两个集合,一个是 orders,另一个是 customers,orders 集合中有一个字段 customer_id,表示订单所属的客户。现在我们想要按照客户性别统计他们的订单数量。可以使用以下代码实现: ```java import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.aggregation.Fields; import org.springframework.data.mongodb.core.aggregation.LookupOperation; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class OrderRepositoryImpl implements OrderRepositoryCustom { private final MongoTemplate mongoTemplate; public OrderRepositoryImpl(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } @Override public List<OrderCountByGender> countOrdersByGender() { LookupOperation lookupOperation = LookupOperation.newLookup() .from("customers") .localField("customer_id") .foreignField("_id") .as("customer"); Aggregation aggregation = Aggregation.newAggregation( lookupOperation, Aggregation.project("customer.gender"), Aggregation.group("customer.gender").count().as("count"), Aggregation.project(Fields.fields("count")).and("gender").previousOperation() ); return mongoTemplate.aggregate(aggregation, "orders", OrderCountByGender.class).getMappedResults(); } } ``` 其中 OrderCountByGender 是一个 POJO 类,用于存储按照性别统计的订单数量: ```java public class OrderCountByGender { private String gender; private Long count; // getters and setters } ``` 在上面的代码中,我们使用 LookupOperation 将 orders 集合中的 customer_id 与 customers 集合中的 _id 关联起来。然后,使用 Aggregation 进行分组统计,最后使用 mongoTemplate.aggregate 方法执行聚合操作,并将结果映射到 OrderCountByGender 类型的对象列表中返回。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值