Spring Boot整合Spring Data MongoDB 常用API

环境

  • MacOS
  • MongoDB 5.0.2
  • Spring Boot 2.4.0

配置

创建一个maven项目,引入依赖jar包,配置pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.0</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.71</version>
    </dependency>
</dependencies>

修改 application.properties为以下内容:

spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
#spring.data.mongodb.username=
#spring.data.mongodb.password=
spring.data.mongodb.database=user

项目结构为:

pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── cn
    │   │       └── coder47
    │   │           ├── Application.java
    │   │           ├── model
    │   │           │   └── User.java
    │   │           └── repository
    │   │               └── UserRepository.java
    │   └── resources
    │       └── application.properties
    └── test
        └── java
            └── cn
                └── coder47
                    ├── MongoRepositoryTest.java
                    └── MongoTemplateTest.java

Model

@Data
public class User {

    private Integer id;

    private String username;

    private String phone;

    private String sex;

    private String nickname;

    private Date lastModified;
}

Repository

public interface UserRepository extends MongoRepository<User, Integer> {
}

常用API

Spring Data主要提供了两个操作MongDB的类和接口,分别是MongoRepositoryMongoTemplateMongoRepository提供了简单的文档CRUD接口,MongoTemplate提供了集合CRUD和文档CRUD接口,其中也包含了文档的复杂条件查询和聚合分析接口。

MongoTemplate
@Slf4j
@SpringBootTest
public class MongoTemplateTest {

    @Autowired
    MongoTemplate mongoTemplate;

    private static final String COLLECTION_NAME = "user";

    /**
     * 删除集合
     */
    @Test
    public void dropCollection() {
        mongoTemplate.dropCollection(COLLECTION_NAME);
    }

    /**
     * 查询集合名称列表
     */
    @Test
    public void getCollection() {
        Set<String> collectionNames = mongoTemplate.getCollectionNames();
        log.info(JSON.toJSONString(collectionNames));
    }

    /**
     * 创建集合
     */
    @Test
    public void createCollection() {
        boolean exists = mongoTemplate.collectionExists(COLLECTION_NAME);
        if (exists) {
            log.info("集合已经存在");
            return;
        }
        CollectionOptions collectionOptions = CollectionOptions.empty()
                .size(6142800) // 为固定集合指定一个最大值,即字节数
                .maxDocuments(10000) // 指定固定集合中包含文档的最大数量。
                //.capped() 如果为 true,则创建固定集合。固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档。
                .collation(Collation.of(Locale.CHINA.getLanguage()));// 定制中文排序规则
        mongoTemplate.createCollection(COLLECTION_NAME, collectionOptions);
    }

    /**
     * 插入文档
     */
    @Test
    public void insert() {
        User user = new User();
        user.setId(1);
        user.setUsername("张三");
        user.setPhone("131000281912");
        user.setNickname("小三");
        user.setSex("男");
        user.setLastModified(new Date());
        mongoTemplate.insert(user);

        User user1 = new User();
        user1.setId(2);
        user1.setUsername("李四");
        user1.setPhone("132000281912");
        user1.setNickname("小四");
        user1.setSex("男");
        user1.setLastModified(new Date());
        mongoTemplate.insert(user1);
    }

    /**
     * 查询文档
     */
    @Test
    public void findAll() {
        List<User> all = mongoTemplate.findAll(User.class, COLLECTION_NAME);
        log.info(JSON.toJSONString(all));
    }

    /**
     * 根据id查询文档
     */
    @Test
    public void findById() {
        User user = mongoTemplate.findById(1, User.class, COLLECTION_NAME);
        log.info(JSON.toJSONString(user));
    }

    /**
     * 分页条件查询文档
     */
    @Test
    public void findByCondition() {
        // 条件 跟sql写法类似
        Query query = new Query(Criteria
                .where("phone").is("131000281912")
                .and("id").gte(1)
                .and("username").in("张三", "李四"));

        // 排序
        query.with(Sort.by(Sort.Order.asc("username")));

        // 分页
        Pageable pageable = PageRequest.of(0, 10);
        query.with(pageable);

        List<User> users = mongoTemplate.find(query, User.class, COLLECTION_NAME);
        long count = mongoTemplate.count(query, User.class);

        Page<User> page = PageableExecutionUtils.getPage(users, pageable, () -> count);
        log.info(JSON.toJSONString(page));
    }

    @Test
    public void getCount() {
        Query query = new Query(Criteria
                .where("phone").is("131000281912")
                .and("id").gte(1)
                .and("username").in("张三", "李四"));

        long count = mongoTemplate.count(query, User.class, COLLECTION_NAME);
        log.info(JSON.toJSONString(count));
    }

    /**
     * 更新文档
     */
    @Test
    public void update() {
        User user = new User();
        user.setId(2);
        user.setUsername("李四");
        user.setPhone("131000281922");
        user.setNickname("小四");
        user.setSex("女");
        user.setLastModified(new Date());
        mongoTemplate.save(user, COLLECTION_NAME);
    }

    /**
     * 删除文档
     */
    @Test
    public void deleteById() {
        mongoTemplate.remove(new Query(), User.class, COLLECTION_NAME);
    }

    /**
     * 聚合
     */
    @Test
    public void aggregate() {
        // count
        Aggregation countAggregation = Aggregation.newAggregation(
                count().as("count")
        );
        AggregationResults countAggregate = mongoTemplate.aggregate(countAggregation, User.class, HashMap.class);
        log.info(JSON.toJSONString(countAggregate));

        // sum
        Aggregation sumAggregation = Aggregation.newAggregation(
                match(Criteria.where("sex").in("男", "女")),
                group().max("id").as("sum")
        );

        AggregationResults sumAggregate = mongoTemplate.aggregate(sumAggregation, User.class, HashMap.class);
        log.info(JSON.toJSONString(sumAggregate));

        // max
        Aggregation maxAggregation = Aggregation.newAggregation(
                group().max("id").as("max")
        );

        AggregationResults maxAggregate = mongoTemplate.aggregate(maxAggregation, User.class, HashMap.class);
        log.info(JSON.toJSONString(maxAggregate));
    }
}
MongoRepository
@Slf4j
@SpringBootTest
public class MongoRepositoryTest {

    @Autowired
    UserRepository userRepository;

    /**
     * 插入文档
     */
    @Test
    public void insert() {
        User user = new User();
        user.setId(1);
        user.setUsername("张三");
        user.setPhone("131000281912");
        user.setNickname("小三");
        user.setLastModified(new Date());
        userRepository.insert(user);
    }

    /**
     * 分页查询文档
     */
    @Test
    public void findAll() {
        Sort sort = Sort.by(Sort.Order.asc("id"));
        PageRequest pageRequest = PageRequest.of(0, 10, sort);
        Page<User> page = userRepository.findAll(pageRequest);
        log.info(JSON.toJSONString(page));
    }

    /**
     * 统计文档个数
     */
    @Test
    public void count() {
        long count = userRepository.count();
        log.info(JSON.toJSONString(count));
    }

    /**
     * id查询
     */
    @Test
    public void findById() {
        User user = userRepository.findById(1).orElse(null);
        log.info(JSON.toJSONString(user));
    }

    /**
     * 条件查询
     */
    @Test
    public void findByCondition() {
        User user = new User();
        user.setUsername("张");
        user.setPhone("131000281912");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withIgnoreNullValues()
                .withIgnorePaths("id", "nickname", "lastModified")
                .withMatcher("username", ExampleMatcher.GenericPropertyMatcher::endsWith)
                .withMatcher("username", ExampleMatcher.GenericPropertyMatcher::startsWith);

        Example example = Example.of(user, matcher);
        List list = userRepository.findAll(example);
        log.info(JSON.toJSONString(list));
    }

    /**
     * 更新文档
     */
    @Test
    public void update() {
        User user = new User();
        user.setId(1);
        user.setUsername("张三1");
        user.setPhone("131000281922");
        user.setNickname("小三1");
        user.setLastModified(new Date());
        userRepository.save(user);
    }

    /**
     * 删除文档
     */
    @Test
    public void deleteById() {
        userRepository.deleteById(1);
    }
}

总结

以上为Spring Data MongoDB 的常用API,更多用法可以参考:Spring Data MongoDB文档

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值