SpringBoot与MongoDB构建RESTful风格
sprinboot与mongodb构建restful风格
所有的请求模式和jpa构建的restful一致
1、pom.xml
spring-boot-starter-data-rest
spring-boot-starter-data-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.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.lc</groupId>
<artifactId>jpa-rest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jpa-rest</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、实体bean
@Setter
@Getter
@ToString
public class Book {
private Integer id;
private String name;
private String author;
}
3、dao接口配置
public interface BookDao extends MongoRepository<Book,Integer> {
}
4、yaml配置
spring:
data:
mongodb:
# mongodb每个库都有自己的认证方式
authentication-database: lc
username: root
password: 147258369
port: 27017
database: lc
uri: mongodb://root:147258369@47.96.141.44:27017/lc
# host: 47.96.
5、接口测试
1、添加数据
post: http://localhost:8080/books
{
"name": "曹雪芹",
"author": "红楼梦",
"_links": {
"self": {
"href": "http://localhost:8080/books/1"
},
"book": {
"href": "http://localhost:8080/books/1"
}
}
}
2、查询所有
get: http://localhost:8080/books
{
"_embedded": {
"books": [
{
"name": "曹雪芹",
"author": "红楼梦",
"_links": {
"self": {
"href": "http://localhost:8080/books/1"
},
"book": {
"href": "http://localhost:8080/books/1"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/books{?page,size,sort}",
"templated": true
},
"profile": {
"href": "http://localhost:8080/profile/books"
}
},
"page": {
"size": 20,
"totalElements": 1,
"totalPages": 1,
"number": 0
}
}