REST API: Java Spring Boot and MongoDB

Java 使用Spring-Batch 前言: 什么是Spring的批处理?简而言之,批处理执行作业。单个作业至少包含一个步骤。 前段时间公司需求让在现有系统中添加新功能。该系统必须从外部数据库获取数据。该外部数据库可通过REST API访问,但我们无法“动态”使用它,因为它花了太多时间。因此,我们决定从外部数据库和我们系统使用的数据库中复制数据。换句话说,我们必须下载我们需要的东西并将其存储到我们的数据库中。之后我... 阅读详情

REST API: Java Spring Boot and MongoDB

第一次做翻译的如果有没翻译准确的欢迎指出,Typora上面编辑的文章移植到CSDN格式就有很多问题,如有需要可以到我的CSDN下载中下载(https://download.csdn.net/download/ccmedu/11442425)或者直接邮箱艾特我本人。

作者是:Thomas Gleason

REST API: Java Spring Boot and MongoDB

REST API:Java Spring Boot 和 MongoDB

Creating a RESTful web service using the Spring Boot framework and MongoDB

 

创建一个rest风格的web 服务项目,使用springboot 框架和mongodb技术。

 

Why Spring Boot?

为什么选择spring boot呢?

The Java Spring Boot framework provides a powerful set of tools for web development on both the front-end and back-end. It has built-in configuration for security and database access, as well as simple request mappings. This framework is highly configurable and makes web development extremely simple.

Java spring boot 框架为web开发的前后端提供了一个强大的工具集。它含有内置的为了安全和数据库访问的配置,以及简单的请求映射。这个框架是高度可配置的并且使web开发变的极其简单。

Why MongoDB?

为什么选择MongoDB呢?

Mongo is quickly growing in popularity among NoSQL databases. Read more about NoSQL and its benefits here. MongoDB, specifically, is perfect for developing a REST API with Spring Boot for a couple of key reasons:

  • Data is stored in MongoDB as JSON

  • Spring Boot provides a powerful MongoDB connector

Mongo 在受欢迎的非关系型数据库中迅速增长。在这可以读到更多关于非关系型数据库以及它们的优势。MongoDb 具体来说,由于以下两个关键的原因是非常适合集成springboot来开发一个rest风格的API:

数据存储在MongoDB中的格式是JSON的

Spring Boot 提供了一个强大的MongoDB 连接器

Tools Used in this Tutorial

本教程中使用的工具如下所示

  1. Java

  2. Spring Boot

  3. Maven

  4. MongoDB

  5. Postman

Step 1: Creating a Database

第一步:创建一个数据库

This tutorial assumes that you already have an accessible instance of MongoDB that you can connect to. For more information on getting started with MongoDB, visit their online tutorial.

Let us start by creating a test database. I will call mine “rest_tutorial” using the following command in the MongoDB shell, or through a database manager like MongoDB Compass:

本教程是假定你已经有了一个可以访问并且可以连接的MongoDB的实例。想了解更多的MongoDB的入门信息可以访问他们的在线教程。

让我们开始创建一个测试的数据库。我将会调用我自己的"rest_tutorial",通过使用如下的在MongoDB的shell中的命令,或者通过一个数据库的管理工具类似于"MongoDB Compass":

use rest_tutorial;
db.createCollection(“pets”);
db.createCollection(“pets”);
{
  “name” : “Spot”,
  “species” : “dog”,
  “breed” : “pitbull”
}
db.pets.insertMany([
  {
    “name” : “Spot”,
    “species” : “dog”,
    “breed” : “pitbull”
  },
  {
    “name” : “Daisy”,
    “species” : “cat”,
    “breed” : “calico”
  },
  {
    “name” : “Bella”,
    “species” : “dog”,
    “breed” : “australian shepard”
  }
]);

使用 db.pets.find({}); 查询这个集合时,MongoDB会为每个文档自动创建一个唯一的unique_id字段,用来使查找和编辑文档更加方便。

Querying the collection with db.pets.find({}); reveals that MongoDB automatically assigns a unique _id field to each document to make it easier to find and edit documents.

 

我们使用如下命令为这个集合添加数据:

We can add data to the collection with the following command:

一旦这个集合被创建了,我们需要我们需要添加一些数据!这个集合将会包含各种宠物的名字,品种,和种类。因此单文档格式如下所示:

Once the collection is created, we need to add some data! This collection will hold the names, breeds, and species of various pets, so a single document would be formatted as follows:

在MongoDB中,集合类似于在关系型数据库中的表-他们持有数据而我们将会使用我们的REST API去查询数据。我将会创建一个简单的集合,包含不同类型的宠物的数据。使用如下命令去创建这个集合。

In MongoDB, collections are analogous to tables in a relational database — they hold the data that we will be querying using our REST API. I will be creating a sample collection that will hold data about different types of pets. Let’s create the collection with the following command:

第二步:添加一个MongoDB的集合和数据

Step 2: Adding a MongoDB Collection and Data

使用上面这个命令将会在MongoDB中创建一个新的数据库,我们可以用于我们的教程。

This will create a new database in MongoDB that we can use for our tutorial.

Using Spring Initializr to Create a Project

使用Spring Initializr去创建一个项目

Spring offers a tool called the Spring Initializr to help jump-start your Spring Boot project. Access the Initializr at start.spring.io, and enter the following information:

  • Group: This is the package name Example: com.example.gtommee

  • Artifact: This is the project name Example: rest_tutorial

  • Dependencies: These are the features that will be added to your project (remember, you can always add these later) Our tutorial will use the “Web” and “MongoDB” dependencies

Spring提供了一个工具叫做Spring Initializr,来帮助你的Spring Boot 项目快速启动。进入Initializr官网,它网址是 start.spring.io,输入如下信息:

Group:包名字

填写示例:com.example.gtommee

Artifact:项目名字

填写示例:rest_tutorial

Dependencies:这些内容将会被添加到你的项目中去(请记住,你可以要晚一点再添加上它们)

我们的教程将会使用这个"Web"和“MongoDB” 的依赖

Then click Generate Project to download a .zip file with the basic project structure.

然后点击Generate Project 去下载基础项目结构的a.zip压缩包文件

 

Adding Model to Spring Boot Project

为这个SpringBoot项目添加模型

With the project downloaded from the Spring Initializr, you can now open it in your favorite IDE to begin editing the project. First, we will want to add a pets model, so that Spring will know what kind of data the database will return. We can do this by creating a new folder in src/main/java/[package name]/ called “models”. In the new “models” folder, we can create a file called Pets.java. This Java class will hold the basic structure of a document in the “pets” collection, so the class looks as follows

 

从Spring Initializr官网下载了这个项目后,你可以用你最喜欢的IDE工具打开它,开始编辑这个项目。首先我们想要添加一个宠物的模型,这样以来Spring就会知道数据库将会返回哪种类型的数据。我们为了实现它可以在 src/main/java/[package name]/ 下边创建一个新的文件夹叫做"models"。在这个新的"models"的文件夹中,我们可以创建一个文件名字叫做Pets.java。这个Java类将会包含一个在宠物集合中的基础结构文档。因此这个类看起开如下所示:

package com.example.gtommee.rest_tutorial.models;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
public class Pets {
  @Id
  public ObjectId _id;
 
  public String name;
  public String species;
  public String breed;
 
  // Constructors
  public Pets() {}
 
  public Pets(ObjectId _id, String name, String species, String breed) {
    this._id = _id;
    this.name = name;
    this.species = species;
    this.breed = breed;
  }
 
  // ObjectId needs to be converted to string
  public String get_id() { return _id.toHexString(); }
  public void set_id(ObjectId _id) { this._id = _id; }
 
  public String getName() { return name; }
  public void setName(String name) { this.name = name; }
 
  public String getSpecies() { return species; }
  public void setSpecies(String species) { this.species = species; }
 
  public String getBreed() { return breed; }
  public void setBreed(String breed) { this.breed = breed; }
}

文中的@Id注解告诉Spring这个_id字段将会被作为主标识符所使用。类的其他部分包含了这个Pets(宠物)对象的基本构造函数,getters方法,setters方法。

The @Id annotation tells spring that the _id field will be used as the primary identifier. The rest of the class contains the basic constructors, getters, and setters for the Pets object.

Adding Repository to Spring Boot Project

为SpringBoot项目添加仓库

Now that we have a model that identifies the data structure stored in the database to Spring Boot, we can create the connector between the model and MongoDB. This is done through a Repository interface. We can create this first by making a new folder called “repositories” in src/main/java/[package name]/.

现在,在SpringBoot中,我们有一个模型去标识的数据库中数据存储结构。我们可以创建一个连接器在模型和MongoDB。通过一个仓库的接口来实现。我们可以创建这个,通过在src/main/java/[package name]/`目录下创建一个新的文件夹,名字是repositories。

In the new “repositories” folder, we can create a file called PetsRepository.java. The name of this repository is extremely important because it tells MongoDB the collection that it will be querying (in this case, the pets collection). This interface will extend the MongoRepository class, which already contains generic methods like save (for creating/updating documents) and delete (for removing documents), but we will need to specify additional methods ourselves.

在新的名字是“repositories” 的文件夹下,我们可以创建一个名字叫PetsRepository.java的文件。这个repository的名字是极其重要的,因为它会告诉MongoDB,哪个集合将会被执行(在这个例子中,宠物就是这个集合)。这个接口会继承MongoRepository类,并且这个类中已经包含了基础方法比如说存储(用于创建或者新增文件)以及删除(用于移除文件),但是我们将需要我们自己指定的额外的方法。

Luckily, we do not need to manually implement these queries, we can simply use Spring Boot’s repository naming conventions, and the MongoRepository will intelligently construct the queries at runtime. This means that our interface will be extremely simple, as follows:

幸运的是我们不需要手动实现这些查询方法,我们可以很简单的去使用SpringBoot 框架中叫做约定的仓储 ,

MongoRepository将会在运行时智能的构造该查询方法。这就意味着我们的接口将会变得极其简单,如下所示:

package com.example.gtommee.rest_tutorial.repositories;
import com.example.gtommee.rest_tutorial.models.Pets;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface PetsRepository extends MongoRepository<Pets, String> {
  Pets findBy_id(ObjectId _id);
}

Adding the MongoDB Connection Info

To tell Spring the connection information for our MongoDB, we will need to add conection details to the application.properties file, located in the “src/main/resources” folder. Add the following lines to the file, replacing the information in brackets with the information specific to your MongoDB instance:

 

我们需要为application.properties 文件添加连接细节,这样以来就可以告知Spring框架去连接MongoDB的信息,这个application.properties 文件位于“src/main/resources” 目录下的文件夹内。添加下列行到该文件中去。并且用你的MongoDB实例的具体信息去替代括号中的信息。

spring.data.mongodb.host=[host]
spring.data.mongodb.port=[port]
spring.data.mongodb.authentication-database=[authentication_database]
spring.data.mongodb.username=[username]
spring.data.mongodb.password=[password]
spring.data.mongodb.database=rest_tutorial

这就是Spring连接数据库的所有信息

This is all the information that Spring will need to connect to the database.

Creating REST Controller

创建rest风格的Controller

Spring should now be able to connect to MongoDB, so now we can establish the enpoints that we can contact to interact with the database. This will be done in a Spring Rest Controller, which uses Request Mappings to map requests with functions. We can create a Rest Controller by adding a file called PetsController.java to the src/main/java/[package name]/ folder. The basic file structure will look as follows:

现在Spring应该可以连接到MongoDB了,那么现在我们可以建立同数据库直接相互联系的端点了。这个将会在Spring中的Rest风格的Controller类中实现它。通过使用请求映射将请求映射到方法中。通过在src/main/java/[package name]/文件夹下添加一个名字为PetsController.java的类,这样我们就可以创建一个Rest风格的controller。这个基本的文件结构看起来就像如下展示:

package com.example.gtommee.rest_tutorial;
import com.example.gtommee.rest_tutorial.models.Pets;
import com.example.gtommee.rest_tutorial.repositories.PetsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(“/pets”)
public class PetsController {
  @Autowired
  private PetsRepository repository;
}

这个@RestController 注解会告诉Spring 这个类将会被URL所请求,并且将会返回数据给请求者。这个@RestController 注解的作用是指定了会被处理的基本的URL,任何以“/pets” 开头的主机的请求将会被指定到此Controller(控制器)。

The @RestController annotation tells Spring that this class will requested by URL and will return data to the requester. The @RequestMapping annotation specifies the base URL that the controller will be handling, so any request to the host starting with “/pets” will be directed to this controller. The @Autowired annotation creates an instance of the PetsRepository object that will allow us to access and modify the pets database.

这个@RestController 注解会告诉Spring 这个类将会被URL所请求,并且将会返回数据给请求者。这个@RestController 注解的作用是指定了会被处理的基本的URL,任何以“/pets” 开头的主机的请求将会被指定到此Controller(控制器)。这个@Autowired 注解创建了一个PetsRepository对象是实例,使用这个对象将会允许我们访问和修改这个pets的数据。

Adding the REST Endpoints

添加rest风格的终端

All of the following enpoints will be added directly into the PetsController class.

以下所有的端点将会被直接添加到PetsController类中去。

GET

get

@RequestMapping(value = “/”, method = RequestMethod.GET)
public List<Pets> getAllPets() {
  return repository.findAll();
}
@RequestMapping(value = “/{id}”, method = RequestMethod.GET)
public Pets getPetById(@PathVariable(“id”) ObjectId id) {
  return repository.findBy_id(id);
}

The first mapping takes any GET requests to the host with a URL of /pets/and maps them to the getAllPets() method, which requests all documents from the pets collection.

第一个映射是表示任何在URL中含有/pets/字样的get请求都可以去访问主机,并且映射他们到这个getAllPets() 方法找那个去,可以请求pets集合中所有文件。

 

The second mapping takes and GET requests to the host with a URL of /pets/ followed by an ObjectId and maps them to the getPetById()method, which searches the pets collection for the document with an _idfield equal to the ObjectId in the URL.

第二个映射表示任何在URL中含有/pets/字样,并且后边是对象的ID的get请求都可以访问该主机,并且映射到getPetById()方法中去,查找到/pets/集合文档中的_id字段与URL中对象ID相等的内容。

PUT

@RequestMapping(value = “/{id}”, method = RequestMethod.PUT)
public void modifyPetById(@PathVariable(“id”) ObjectId id, @Valid @RequestBody Pets pets) {
  pets.set_id(id);
  repository.save(pets);
}

这个映射期待一个请求体(Json格式的),每个字段都是Pets对象所包含的(名字,特征,和品种)。这个ID在请求的url中对应的是文档中将要被修改的_id字段。

This mapping expects a request body (in JSON format) with each of the fields that a Pets object contains (name, species, and breed). The id in the request URL is the _id of the document to be modified.

POST

@RequestMapping(value = “/”, method = RequestMethod.POST)
public Pets createPet(@Valid @RequestBody Pets pets) {
  pets.set_id(ObjectId.get());
  repository.save(pets);
  return pets;
}

这个映射期待一个请求体(Json 格式的),里面的每一个字段都是Pets实体对象中所包含的(名字,特征,和品种),并且给他分配一个新的对象ID。这个对象之后会被插入到这个pets集合中去,兵器新的Pets对象将会被返回给请求者。

This mapping expects a request body (in JSON format) with each of the fields that a Pets object contains (name, species, and breed), and assigns it a new ObjectId. This object is then inserted into the pets collection, and the new Pets object is returned.

这个映射期待一个请求体(Json 格式的),里面的每一个字段都是Pets实体对象中所包含的(名字,特征,和品种),并且给他分配一个新的对象ID。这个对象之后会被插入到这个pets集合中去,兵器新的Pets对象将会被返回给请求者。

DELETE

@RequestMapping(value = “/{id}”, method = RequestMethod.DELETE)
public void deletePet(@PathVariable ObjectId id) {
  repository.delete(repository.findBy_id(id));
}

这个端点携带了pets集合的文档中的_id字段,并且可以从集合中删除该文档。

This endpoint takes the _id of a document in the pets collection and removes that document from the collection.

Completed Controller

package com.example.gtommee.rest_tutorial;
import com.example.gtommee.rest_tutorial.models.Pets;
import com.example.gtommee.rest_tutorial.repositories.PetsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.List;@RestController
@RequestMapping(“/pets”)
public class PetsController {
  @Autowired
  private PetsRepository repository;
 
  @RequestMapping(value = “/”, method = RequestMethod.GET)
  public List<Pets> getAllPets() {
    return repository.findAll();
  }  @RequestMapping(value = “/{id}”, method = RequestMethod.GET)
  public Pets getPetById(@PathVariable(“id”) ObjectId id) {
    return repository.findBy_id(id);
  }
 
  @RequestMapping(value = “/{id}”, method = RequestMethod.PUT)
  public void modifyPetById(@PathVariable(“id”) ObjectId id, @Valid @RequestBody Pets pets) {
    pets.set_id(id);
    repository.save(pets);
  }
 
  @RequestMapping(value = “/”, method = RequestMethod.POST)
  public Pets createPet(@Valid @RequestBody Pets pets) {
    pets.set_id(ObjectId.get());
    repository.save(pets);
    return pets;
  }
 
  @RequestMapping(value = “/{id}”, method = RequestMethod.DELETE)
  public void deletePet(@PathVariable ObjectId id) {
    repository.delete(repository.findBy_id(id));
  }
}

Now that the controller has all of our endpoints, we can begin testing our API! From the command line, in the project root, run the mvn spring-boot:run command to compile the code and start the Spring server with the default port 8080.

测试你的API( 应用程序接口)

Testing Your API

测试你的API( 应用程序接口)

Now that the controller has all of our endpoints, we can begin testing our API! From the command line, in the project root, run the mvn spring-boot:run command to compile the code and start the Spring server with the default port 8080.

现在这个控制器含有我们所有的端点,我们可以开始去测试我们的接口了。从命令行进入如项目的根目录,运行

mvn spring-boot:run命令,去变异这些代码,并且用默认端口号8080去启动Spring的服务器。

Once the server starts, you are free to test your API however you choose.

POST 'http://localhost:8080/pets'

 

用post方式访问URL为 `'http://localhost:8080/pets'的地址且

With body : {“name” : “Liam”, “species” : “cat”, “breed” : “tabby”}

请求体是: `{“name” : “Liam”, “species” : “cat”, “breed” : “tabby”}

and header : Content-Type: application/json

请求头是json格式的

Returns:

返回值是

{
  “_id”: “5aecef5b6d55754834124df3”,
  “name”: “Liam”,
  “species”: “cat”,
  “breed”: “tabby”
}

PUT ‘http://localhost:8080/pets/5aecef5b6d55754834124df3

用put方式访问URL为‘http://localhost:8080/pets/5aecef5b6d55754834124df3`的地址且

With body : {“name” : “Liam”, “species” : “cat”, “breed” : “siamese”}

请求体是:{“name” : “Liam”, “species” : “cat”, “breed” : “siamese”}

and header : Content-Type : application/json

请求头是json格式的

Returns:

返回值是

empty response

空的响应体

GET ‘http://localhost:8080/pets/5aecef5b6d55754834124df3’

用GET方式访问URL是‘http://localhost:8080/pets/5aecef5b6d55754834124df3’的地址

Returns:

返回值是:

{
  “_id”: “5aecef5b6d55754834124df3”,
  “name”: “Liam”,
  “species”: “cat”,
  “breed”: “siamese”
}

DELETE ‘http://localhost:8080/pets/5aecef5b6d55754834124df3’

用delete方法访问地址为 ‘http://localhost:8080/pets/5aecef5b6d55754834124df3’的URL

Returns:

返回值是:

empty response

返回值是:

Returns:

用get方法访问地址是‘http://localhost:8080/pets’的URL

GET ‘http://localhost:8080/pets’

返回值是:

[
  {
    “_id”: “5aeccb0a18365ba07414356c”,
    “name”: “Spot”,
    “species”: “dog”,
    “breed”: “pitbull”
  },
  {
    “_id”: “5aeccb0a18365ba07414356d”,
    “name”: “Daisy”,
    “species”: “cat”,
    “breed”: “calico”
  },
  {
    “_id”: “5aeccb0a18365ba07414356e”,
    “name”: “Bella”,
    “species”: “dog”,
    “breed”: “australian shepard”
  }
]

Future Articles

未来的文章

Now you have created a REST API using Java Spring Boot and MongoDB! In future articles, I will explain how to add additional features to your API, such as authentication! I will list the articles here as they become availible.

现在你创建了一个使用Java SpringBoot 框架和MongoDB数据库的rest风格的应用程序接口!在为了的文章里面我将会解释如何在你的应用程序接口中去添加其他的功能。例如权限验证!我将会在这列出这些文章,使他们变的可用。

9、从Spring Data JPA到MongoDB及REST API开发全解析 本文全面解析了从Spring Data JPA的基础操作到MongoDB的安装与使用,并深入探讨了如何利用Spring Boot构建RESTful Web服务。内容涵盖了仓库接口重构、排序与分页功能、MongoDB的基本操作、Spring Data MongoDB的配置与实体映射、以及REST API的设计与实现。适合希望掌握现代Web开发技术栈的开发者阅读。 阅读详情

相关推荐

Spring Data REST与MongoDB的集成实践

本文还有配套的精品资源,点击获取 简介:Spring Data REST与MongoDB的结合提供了一种强大的方式,将Java应用与NoSQL数据库进行集成,实现数据的灵活管理和RESTful服务的快速暴露。本文将深入探讨如何在Spring Boot应用中配置和使用MongoDB,创建实体、仓库,并通过Spring Data REST使其变成RESTful API。我们将讨...

weixin_42577735的博客 1061

Spring Boot 中 MongoDB构建 RESTful 风格应用

Spring Boot 中 MongoDB构建 RESTful 风格应用 RESTful ,到现在相信已经没人不知道这个东西了吧!关于 RESTful 的概念,我这里就不做过多介绍了,传统的 Struts 对 RESTful 支持不够友好 ,但是 SpringMVC 对于 RESTful 提供了很好的支持,常见的相关注解有: @RestController @GetMapping @PutMapp...

liuzuoping的博客 505

rest-springboot:使用mongodb API的REST API

休息弹簧靴 使用Spring Boot和MongoDB的图书搜索者的REST API。 技术领域 Spring启动2.0.2 MongoDB API 3.6.3 Bootstrap 4.1.1 Bootswatch“ Litera”主题 jQuery的 如何开始... 安装MongoDB并使用“ booksearcher ”数据库,创建一个“ books ”集合。 使用mongoimport函数将导入books集合中: mongoimport --db booksearcher --collection books --file /books.json 运行BooksearcherApplication.java类,此引导将在localhost:8090上加载一个REST服务。 要使用诸如cURL或邮递员之类的客户端工具测试REST API,请使用以下路径: /booksea

如何构建SpringBoot MongoDb RestfulApi

打开pom.xml文件,添加Spring Data Rest和Spring Data Mongo依赖项: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</a...

weixin_44174165的博客 460

CTF全能工具箱ProV2:集成AI与94GB离线资源库,打造无网环境下的智能解题流水线

CTF全能工具箱ProV2是一款专为线下CTF比赛设计的All-in-One离线解决方案。它集成了94GB的庞大离线资源库,涵盖Web、逆向、Pwn等全方向工具链与知识库,并创新性地内置了本地AI大模型,可在断网环境下提供智能解题辅助,实现从信息收集到漏洞利用的智能流水线作业,极大提升比赛效率。

weixin_29240343的博客 436

MAX96712在车载摄像头系统中的带宽分配与传输能力计算解析

在计算摄像头带宽与传输接口的关系时,需要考虑视频流的像素分辨率、帧率、颜色深度等因素。以 MAX96712 这种 GMSL2 产品为例,它支持每个链路在正向方向以 3Gbps 或 6Gbps 的固定速率工作。

weixin_43199439的博客 3344

使用Spring Boot和MongoDB创建REST API

今年,我以不同的方式迎接圣诞节:我是Java Advent Calendar的一部分。 让我们为圣诞节做准备: Spring Boot是一个自以为是的框架,可简化Spring应用程序的开发。 它使我们摆脱了复杂配置文件的束缚,并帮助我们创建了不需要外部servlet容器的独立Spring应用程序。 这听起来实在令人难以置信,但Spring Boot确实可以完成所有这一切 。 这篇...

最佳 Java 编程 330

Vue3项目实战:CKEditor5富文本编辑器从安装到隐藏不需要的功能

本文详细介绍了在Vue3项目中集成并深度定制CKEditor5富文本编辑器的完整流程。通过分析其模块化架构,指导开发者从标准构建出发,移除图片、表格等冗余插件,创建专属轻量构建,从而显著减小打包体积并提升用户体验。文章结合实战代码,涵盖了环境搭建、自定义构建配置、高级优化技巧等关键步骤。

weixin_29016833的博客 289

springboot集成mongodb的基础功能

一、引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> 二、自定义配置MongoTemplate @Configuration public class MongodbConfig { @Value("${s

qq_20161461的博客 695

OpenCv案例(七): 基于OpenCvSharp计算图像的清晰度(自动对焦)

自动对焦,其实是对相机成像的清晰值得计算,若对焦不清晰,成像的清晰度低,视觉效果模糊。若是在工业检测行业,对焦不准确,可能会造成严重后果;对焦准确的图像,其清晰度高,对比度鲜明,层次明显。

qq_37835727的博客 7122

Yolov5自学笔记之一--从入门到入狱,功能强大不要乱用(实现yolov5的基本功能使用流程及训练自己的数据集)

零基础自学yolov5,学会简单使用和训练自己的数据集,在自己工作中使用

qq_41597915的博客 1万+

MongoDB - Java连接MongoDB:Spring Boot集成MongoDB的步骤

本文介绍了在Spring Boot中集成MongoDB的全过程。首先通过Spring Initializr创建项目并添加MongoDB依赖,然后配置连接信息。接着详细说明了如何定义MongoDB实体类,包括使用@Document、@Id等注解进行对象映射。文章还演示了Repository接口的使用方法,涵盖基本CRUD操作、自定义查询和分页功能。通过清晰的代码示例和配置说明,帮助开发者快速掌握Spring Boot与MongoDB的集成开发。

千淘万漉虽辛苦,吹尽狂沙始到金 2万+

40、5G NR射频要求解析

本文详细解析了5G NR射频相关要求,包括参考灵敏度与动态范围的定义、接收机对干扰信号的抗扰性要求(如阻塞、邻道选择性等)、辐射射频要求在FR1和FR2频段的差异,以及多标准无线电基站(MSR)的发展及其对射频要求的影响。内容涵盖测试模型、干扰场景、具体指标和实现挑战,为理解和应用5G NR射频规范提供了全面指导。

qsc901234的博客 256

mongodb安装_使用Spring Boot和MongoDB创建REST API

mongodb安装 今年,我以不同的方式迎接圣诞节:我是Java Advent Calendar的一部分。 让我们为圣诞节做准备: Spring Boot是一个自以为是的框架,可简化Spring应用程序的开发。 它使我们摆脱了复杂的配置文件的束缚,并帮助我们创建了不需要外部servlet容器的独立Spring应用程序。 这听起来实在令人难以置信,但Spring Boot确实可以完成所有这一切...

cunfen8879的博客 217

Flask基础项目:从零到一搭建用户管理系统

本文介绍了一个基于Flask的用户管理系统,具有完整的增删改查功能。系统采用SQLAlchemy ORM进行数据库操作,自动处理SQL注入并首次运行时创建表结构。主要特点包括:实时统计用户总数和平均年龄、智能即时搜索、前后端双重数据验证、邮箱唯一性检查、流畅动画效果和响应式设计。后端使用Flask框架实现RESTful API,前端采用现代化UI设计,支持异步操作不阻塞界面。系统安装简单,只需创建数据库并安装依赖即可运行,适合作为基础用户管理系统的参考实现。

数据知道的博客 3848

爬取Unsplash高清壁纸:Python爬虫实战教程(最新技术)

在当今数字化时代,高清壁纸已经成为人们个性化设备的重要元素。Unsplash作为全球最知名的免费高质量图片网站,汇集了数百万张由全球摄影师贡献的高清图片。然而,Unsplash官网的下载方式需要手动操作,对于需要批量下载壁纸的用户来说效率较低。本文将带你深入探索如何使用Python爬虫技术高效爬取Unsplash高清壁纸,从基础到进阶,全面掌握图片爬取的核心技术。Unsplash成立于2013年,是一个完全免费的图片分享平台。高质量内容:所有图片均由专业摄影师上传,分辨率普遍达到4K以上免费商用。

2201_76125261的博客 939

java rest 通信方式_Spring Boot开发REST服务流程详解

Spring Boot如何开发REST服务REST服务介绍RESTful service是一种架构模式,近几年比较流行了,它的轻量级web服务,发挥HTTP协议的原生的GET,PUT,POST,DELETE。 REST模式的Web服务与复杂的SOAP和XML-RPC对比来讲明显的更加简洁,越来越多的web服务开始采用REST风格设计和实现。例如,Amazon.com提供接近REST风格的Web服务...

weixin_36202642的博客 719

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

使用Spring Boot 2和MongoDB创建Restful API

In modern day software development, It is a prevalent practice for non-static apps or websites to access content resources over the internet which could be sourced from a third-party company or develo...

weixin_26714375的博客 465

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Spring Boot + MongoDB 实战教程:从零构建 RESTful API

JDK: 8+: 2.7.18: MongoDB 官方数据访问层Lombok: 简化实体类代码编写Maven: 项目管理与依赖管理遵循应用场景设计数据结构,优先考虑查询模式适当冗余,避免频繁的 JOIN 操作保持文档扁平化,降低复杂度合理选择嵌套深度,一般不超过 3 层本教程通过一个完整的 RESTful API 项目,展示了如何在 Spring Boot 中集成和使用 MongoDB。从基础的 CRUD 操作到高级的数据分析、性能优化,都进行了详细讲解。

wangchunyu114的博客 517

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Sentinel - 自定义 DataSource:从数据库或 REST API 加载规则

Sentinel 自定义数据源:从数据库或 REST API 加载规则 本文介绍了如何在微服务架构中实现 Sentinel 自定义数据源(DataSource),满足从数据库或 REST API 加载规则的定制化需求。文章分析了实际业务场景中需要自定义数据源的原因,包括业务规则存储在数据库中、规则来源于外部系统等场景。详细讲解了环境准备所需的 Maven 依赖,包括 Sentinel 核心、数据库连接、Web 服务等组件。通过自定义 DataSource,可以突破 Sentinel 内置数据源的限制,实现更

千淘万漉虽辛苦,吹尽狂沙始到金 2万+

使用REST访问MongoDB数据是一种常见的方式,它允许客户端通过HTTP请求与数据库进行交互

实际上,**MongoDB 本身并不直接提供 REST API**。它是一个基于 BSON/JSON 的 NoSQL 数据库,原生使用 **MongoDB Wire Protocol(二进制协议)**,通过官方驱动(如 Node.js 的 `mongodb`、Python 的 `pymongo`)或 Shell(`mongosh`)进行访问。

[Blog][Domain] programb.blog.csdn.net 514

第10篇:Spring Boot NoSQL整合-MongoDB

本文介绍了如何在Spring Boot项目中整合MongoDB。主要内容包括:MongoDB的特点与适用场景;通过Docker快速部署MongoDB;添加Spring Data MongoDB依赖并配置连接;创建文档实体类;使用MongoRepository实现基础CRUD和复杂查询(分页、模糊查询等);通过Controller层实现日志管理API;以及动手实践任务。文章强调了MongoDB无固定Schema的优势,适合存储非结构化数据,并提供了完整的代码示例,帮助开发者快速掌握Spring Boot与Mo

林三的专栏 1087

SpringBoot 之Spring Boot Starter依赖包及作用

作为过来人,小编是整理了很多进阶架构视频资料、面试文档以及PDF的学习资料,针对上面一套系统大纲小编也有对应的相关进阶架构视频资料《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!视频资料[外链图片转存中…(img-FiRGrqAF-1713400074752)][外链图片转存中…(img-u8Z5xyiz-1713400074752)]《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!

2401_84009698的博客 750

如何快速上手eventuate-tram-examples-customers-and-orders:Spring Boot微服务开发入门教程

eventuate-tram-examples-customers-and-orders是一个基于Spring Boot/JPA微服务的编排式saga示例项目,非常适合新手学习微服务架构和事件驱动设计。本文将带你快速入门这个项目,掌握微服务开发的核心技能。 ## 项目架构概览 📊 该项目采用了事件驱动的微服务架构,主要包含三个核心服务:Customer Service、Order Servi

gitblog_00100的博客 739

spring boot构建REST API并用RestTemplate进行测试

spring boot构建REST API并用RestTemplate进行测试 创建spring boot项目 完成相关配置,如数据库配置等 创建一个实体 编写controller,service,dao层 测试 1 创建spring boot项目 spring boot + mongodb 1.1 引入常用依赖 <dependency> <!-- 热部署依赖 --> <groupId>org.springframework.boot</grou

不积跬步无以至千里的博客 390

使用Spring Boot和MongoDB快速进行Web应用原型设计

回到我以前的项目之一,我被要求制作一些应急申请。 时间表紧张,范围简单。 内部编码标准是PHP,因此尝试建立经典的Java EE堆栈将是一个真正的挑战。 而且,说实话,完全过大了。 那怎么办 我趁机尝试了Spring。 我以前使用过它,但是在旧版本中,它被隐藏在此时困扰我的门户软件的技术堆栈中。 我的目标是使WebOps可以简单地放在装有Java的服务器上并运行它。 无需摆弄数十种XML...

最佳 Java 编程 248
上一篇: Java 二分查找算法
下一篇: 给定非负整数 X 的数组形式 A,返回整数 X+K 的数组形式。
ccmedu
博客等级 码龄11年 76粉丝 115原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值