mangodb之二继承MongoRepository操作mangodb

mangodb教程

中文社区

SpringBoot 对mongodb操作存在两种操作方式,一种是MongoRepository,一种是MongoTemplate。这里介绍使用MongoRepository操作mongodb.

实现接口继承MongoRepository,这个接口有了几本的CURD的功能。

 

在CrudRepository接口中封装了很多方法,springboot会自动将继承这个MongoRepository接口的接口进行动态代理,创建接口代理实现对象,交给spring容器管理,在spring动态代理时,会根据jpa查询规范解析自定义的方法,拼接处MQL查询语句,即可实现查询操作.

MongoRepository常用方法:

count()统计总数
count(Example< S > example)条件统计总数
delete(T entities)通过对象信息删除某条数据
deleteById(ID id)通过id删除某条数据
deleteALL(Iterable<? extends T> entities)批量删除某条数据
deleteAll() 清空表中所有的数据
existsById(ID id) 判断数据是否存在
exists(Example< T > example) 判断某特定数据是否存在
findAll() 获取表中所有的数据
findAll(Sort sort) 获取表中所有的数据,按照某特定字段排序
findAll(Pageable pageAble) 获取表中所有的数据,分页查询
findAll(Example< T > example) 条件查询
findAll(Iterable ids) 条件查询
findAll(Example< T > example,Pageable pageable) 条件分页查询
findAll(Example< T > example,Sort sort) 条件查询排序
findOneById(ID id) 通过id查询一条数据
findOne(Example example) 通过条件查询一条数据
insert(S entities) 插入一条数据
insert(Iterable< T > entities) 插入多条数据
save(S entities) 保存一条数据
saveAll(Iterable< T > entities)
save(Iterable< T > iterable) 加入多条数据

注:

 JPA查询规范:

​ 就是定义符合JPA约束的查询方法, 方法格式要求:前缀 + 属性名 + 操作符

​ 前缀:findBy开头或者queryBy开头

​ 属性名:表的某个列(实体对象属性),首字母大写

​ 操作符:and or in

案例:

 windows启动mongodb
d:\Program Files\MongoDB\Server\3.4\bin
mongod.exe --dbpath d:\mongdb\data\db

1,pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.forezp</groupId>
    <artifactId>springboot-mongodb</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot-mongodb</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>generate-docs</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>process-asciidoc</goal>
                        </goals>
                        <configuration>
                            <sourceDocumentName>index.adoc</sourceDocumentName>
                            <backend>html</backend>
                            <attributes>
                                <snippets>${project.build.directory}/snippets</snippets>
                            </attributes>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>


</project>

2,application.properties

spring.data.mongodb.uri=mongodb://mysql3:27017/springboot-db
3,SpringbootMongodbApplication.java
package com.forezp;

import com.forezp.dao.CustomerRepository;
import com.forezp.entity.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootMongodbApplication  {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMongodbApplication.class, args);
    }

}

4,MongoDbController.java

package com.forezp.web;

import com.forezp.entity.Customer;
import com.forezp.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/customer")
public class MongoDbController {
    @Autowired
    private CustomerService customerService;
    @RequestMapping(value ="/list",method = RequestMethod.GET)
    public List<Customer> findAll(){

        return customerService.getAll();
    }
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public void save(@RequestParam(value = "firstName",required = true) String firstName,
            @RequestParam(value = "lastName",required = true) String lastName){ Customer customer=new Customer(); customer.setFirstName(firstName); customer.setLastName(lastName); customerService.insert(customer); } }

5,CustomerService.java

package com.forezp.service;

import com.forezp.entity.Customer;
import java.util.List;

public interface CustomerService {
    List<Customer> getAll();
    void insert(Customer customer);
}

6,CustomerServiceImpl.java

package com.forezp.service;

import com.forezp.dao.CustomerRepository;
import com.forezp.entity.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class CustomerServiceImpl implements CustomerService{

    @Autowired
    private CustomerRepository customerRepository;
    @Override
    public List<Customer> getAll() {
        List<Customer> customerList=    customerRepository.findAll();
        return customerList;
    }

    @Override
    public void insert(Customer customer) {
        customerRepository.insert(customer);
    }


}

7,CustomerRepository.java

package com.forezp.dao;

import java.util.List;
import java.util.Optional;

import com.forezp.entity.Customer;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface CustomerRepository extends MongoRepository<Customer, String> {

     Customer findByFirstName(String firstName);
     List<Customer> findByLastName(String lastName);
     Optional<Customer> findById(String id);

}

8,Customer.java

package com.forezp.entity;

import org.springframework.data.annotation.Id;


public class Customer {

    @Id
    public String id;

    public String firstName;
    public String lastName;

    public Customer() {}

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%s, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }

}

 

使用MongoTemplate案例:

https://www.cnblogs.com/luoxiao1104/p/15145686.html

2022云服务器降价了!阿里云VS腾讯云
阿里云:2022阿里云服务器价格便宜到家了(值得买)
腾讯云:2022腾讯云2核4G服务器8M带宽78元一年(多配置可选)

 

posted on 2022-08-12 17:14  让代码飞  阅读(1102)  评论(0)    收藏  举报

导航

一款免费在线思维导图工具推荐:https://www.processon.com/i/593e9a29e4b0898669edaf7f?full_name=python