中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot中怎么對MongoDB 進行增刪改查操作

發布時間:2021-06-22 15:36:39 來源:億速云 閱讀:305 作者:Leah 欄目:大數據

SpringBoot中怎么對MongoDB 進行增刪改查操作,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

引入MongoDB

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.kailo</groupId>
    <artifactId>kailo-mongodb</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>kailo-mongodb</name>
    <description>MongoDB</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <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>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-mongodb -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
            <version>2.3.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.61</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

添加配置文件:application.properties

server.port=8080
spring.data.mongodb.uri=mongodb://127.0.0.1:27017/xxx
#spring.data.mongodb.host=127.0.0.1
#spring.data.mongodb.port=27017
#spring.data.mongodb.database=xxx
# 默認沒有賬號密碼
#spring.data.mongodb.username=
#spring.data.mongodb.password=

增刪改查代碼:ProductController

@Log4j2
@RequestMapping("/product")
@RestController
public class ProductController {

    private final ProductRepository productRepository;

    private final MongoTemplate mongoTemplate;

    @Autowired
    public ProductController(ProductRepository productRepository, MongoTemplate mongoTemplate) {
        this.productRepository = productRepository;
        this.mongoTemplate = mongoTemplate;
    }

    // 增
    @PostMapping("save")
    public ResponseEntity<Result<Product>> save(Product product) {
        if (!StringUtils.isEmpty(product.get_id())) {
            return ResultUtils.error();
        }
        productRepository.save(product);
        return ResultUtils.ok(product);
    }

    // 刪 單個刪除
    @GetMapping("deleteById")
    public ResponseEntity<Result<String>> deleteById(String id) {
        if (StringUtils.isEmpty(id)) {
            return ResultUtils.error();
        }

        productRepository.deleteById(id);
        return ResultUtils.ok();
    }

    // 刪 批量刪除
    @DeleteMapping("deleteByIds")
    public ResponseEntity<Result<String>> deleteByIds(@RequestBody String[] ids) {
        if (ids == null) {
            return ResultUtils.error();
        }
        List<String> idList = Arrays.asList(ids);

        Iterable<Product> deleteProducts = productRepository.findAllById((Iterable<String>) idList.iterator());
        productRepository.deleteAll(deleteProducts);

        return ResultUtils.ok();
    }

    // 改 單個
    @PostMapping("update")
    public ResponseEntity<Result<Product>> update(Product product) {
        if (StringUtils.isEmpty(product.get_id())) {
            return ResultUtils.error();
        }
        product = productRepository.save(product);
        return ResultUtils.ok(product, "更新成功");
    }

    // 查 查單個
    @GetMapping("findById")
    public ResponseEntity<Result<Product>> findById(String id) {
        Product product = productRepository.findById(id).get();
        return ResultUtils.ok(product);
    }

    // 查 查全部列表
    @GetMapping("findAll")
    public ResponseEntity<Result<List<Product>>> findAll() {
        List<Product> products = productRepository.findAll();
        return ResultUtils.ok(products);
    }

    // 查 分頁查詢
    @GetMapping("findPage")
    public ResponseEntity<Result<Pagination<Product>>> findPage(int page, int size) {
        PageRequest pageRequest = PageRequest.of(page, size, Sort.unsorted());
        Page<Product> productPage = productRepository.findAll(pageRequest);
        log.error(productPage.getClass());
        log.error(productPage.getPageable().getClass());
        return ResultUtils.ok(Pagination.from(productPage));
    }

    // 查 模糊查詢
    @GetMapping("findByNameLike")
    public ResponseEntity<Result<List<Product>>> findByNameLike(String name) {
        List<Product> products = null;
        if (StringUtils.isEmpty(name)) {
            products = productRepository.findAll();
        } else {
            products = productRepository.findByNameLike(name);
        }
        return ResultUtils.ok(products);
    }

    @GetMapping("findPageByNameMongoTemplate")
    public ResponseEntity<Result<List<Product>>> findPageByNameMongoTemplate(int page, int size, String name) {

        Query query = new Query();
        query.addCriteria(Criteria.where("name").regex(name));
        List<Product> products = mongoTemplate.find(query, Product.class);

        return ResultUtils.ok(products);
    }

    // 查 根據條件過濾
    @GetMapping("findPageByNameLike")
    public ResponseEntity<Result<Pagination<Product>>> findPageByNameLike(int page, int size, String name) {
        if (StringUtils.isEmpty(name)) {
            return ResultUtils.error();
        }

        PageRequest pageRequest = PageRequest.of(page, size, Sort.unsorted());

        Query query = new Query();
        query.addCriteria(Criteria.where("name").regex(name));
        List<Product> products = mongoTemplate.find(query, Product.class);

        long total = mongoTemplate.count(query, Product.class);

        return ResultUtils.ok(Pagination.build(products, total, pageRequest));
    }
}

相關代碼

@Data
@Document(value = "xxx")
public class Product implements Serializable  {

    @Id
    @JSONField(name="_id") // fastjson 會過濾 _
    private String _id;
    @Field
    private String name;
    @Field
    private String user;
    @Field
    private Double ccc;

}
public interface ProductRepository extends MongoRepository<Product, String> {

    List<Product> findByNameLike(String name);
}

分頁相關:不用自帶的Page,自定義Pagination,解決序列化和反序列化問題

@Data
public class Pagination<T> implements Serializable {

    private long total;
    private List<T> content = new ArrayList();
    private PaginationRequest pageable;

    public Pagination() {
    }

    public long getTotal() {
        return this.total;
    }

    /**
     * 根據Page,轉化成 Pagination
     *
     * @param page
     * @param <T>
     * @return
     */
    public static <T> Pagination<T> from(Page<T> page) {
        if (page == null) {
            return new Pagination<>();
        }
        return build(page.getContent(), page.getTotalElements(), page.getPageable());
    }

    /**
     * 根據參數,初始化 Pagination
     *
     * @param content
     * @param totalElements
     * @param pageable
     * @param <T>
     * @return
     */
    public static <T> Pagination<T> build(List<T> content, long totalElements, Pageable pageable) {
        Pagination<T> pageResult = new Pagination<>();
        pageResult.setTotal(totalElements);
        pageResult.setContent(content);
        pageResult.setPageable(PaginationRequest.from(pageable));
        return pageResult;
    }

    public int getTotalPages() {
        return this.getSize() == 0 ? 1 : (int) Math.ceil((double) this.total / (double) this.getSize());
    }

    public long getTotalElements() {
        return this.total;
    }

    public boolean hasNext() {
        return this.getNumber() + 1 < this.getTotalPages();
    }

    public int getNumber() {
        return this.pageable.getPageNumber();
    }

    public int getSize() {
        return this.pageable.getPageSize();
    }

    public int getNumberOfElements() {
        return this.content.size();
    }

    public boolean hasPrevious() {
        return this.getNumber() > 0;
    }

    public boolean isFirst() {
        return !this.hasPrevious();
    }

    public boolean isLast() {
        return !this.hasNext();
    }

    public PaginationRequest nextPageable() {
        return this.hasNext() ? this.pageable.next() :  null;
    }

    public PaginationRequest previousPageable() {
        return this.hasPrevious() ? this.pageable.previousOrFirst() : null;
    }

    public boolean hasContent() {
        return !this.content.isEmpty();
    }

    public List<T> getContent() {
        return Collections.unmodifiableList(this.content);
    }

    public Iterator<T> iterator() {
        return this.content.iterator();
    }
}
@Data
public class PaginationRequest implements Serializable {

    private int page;
    private int size;

    public PaginationRequest() {}

    public PaginationRequest(int page, int size) {
        this.page = page;
        this.size = size;
    }

    public static PaginationRequest from(Pageable pageable) {
        Sort sort = pageable.getSort();
        return new PaginationRequest(pageable.getPageNumber(), pageable.getPageSize() );
    }

    public PaginationRequest next() {
        return new PaginationRequest(this.getPageNumber() + 1, this.getPageSize());
    }

    public PaginationRequest previous() {
        return this.getPageNumber() == 0 ? this : new PaginationRequest(this.getPageNumber() - 1, this.getPageSize());
    }

    public PaginationRequest first() {
        return new PaginationRequest(0, this.getPageSize());
    }

    public int getPageSize() {
        return this.size;
    }

    public int getPageNumber() {
        return this.page;
    }

    public long getOffset() {
        return (long)this.page * (long)this.size;
    }

    public boolean hasPrevious() {
        return this.page > 0;
    }

    public PaginationRequest previousOrFirst() {
        return this.hasPrevious() ? this.previous() : this.first();
    }
}
@Data
public class Result<T> implements Serializable {
    private int code;
    private String message;
    private T data;
    private long timestamp = Date.from(Instant.now()).getTime();
}
@Data
public class ResultUtils implements Serializable {

    public static final int SUCCESS = 200;
    public static final int NOT_FOUND = 404;
    public static final int ERROR = 500;

    public static final String OPT_SUCCESS_LANG = "操作成功";
    public static final String OPT_ERROR_LANG = "操作失敗";

    public static <T> ResponseEntity<Result<T>> ok() {
        return ok(OPT_SUCCESS_LANG);
    }

    public static <T> ResponseEntity<Result<T>> ok(String message) {
        return ok(null, message);
    }

    public static <T> ResponseEntity<Result<T>> ok(T data) {
        return ok(data, null);
    }

    public static <T> ResponseEntity<Result<T>> ok(T data, String message) {
        Result<T> result = new Result<>();
        result.setCode(SUCCESS);
        result.setMessage(message);
        result.setData(data);
        return ResponseEntity.ok(result);
    }


    public static <T> ResponseEntity<Result<T>> error() {
        return ok(OPT_ERROR_LANG);
    }

    public static <T> ResponseEntity<Result<T>> error(String message) {
        return ok(null, message);
    }

    public static <T> ResponseEntity<Result<T>> error(T data) {
        return ok(data, null);
    }

    public static <T> ResponseEntity<Result<T>> error(T data, String message) {
        Result<T> result = new Result<>();
        result.setCode(ERROR);
        result.setMessage(message);
        result.setData(data);
        return ResponseEntity.ok(result);
    }
}

關于SpringBoot中怎么對MongoDB 進行增刪改查操作問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

芜湖县| 麻江县| 苗栗县| 张北县| 繁昌县| 库尔勒市| 丹东市| 张家川| 邵阳市| 黑水县| 海口市| 松桃| 甘孜| 昌图县| 区。| 衡山县| 西畴县| 扎兰屯市| 汨罗市| 巴中市| 奈曼旗| 遂昌县| 普定县| 正蓝旗| 庐江县| 蓬莱市| 成都市| 巫溪县| 洪雅县| 崇明县| 永嘉县| 阳城县| 晋城| 榕江县| 资源县| 吉安县| 赤城县| 湟中县| 大埔县| 隆回县| 屏边|