如何构建SpringBoot MongoDb RestfulApi

打开pom.xml文件,添加Spring Data Rest和Spring Data Mongo依赖项:

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

模型类:

public class Customer implements Serializable {
 
    private static final long serialVersionUID = 1L;
 
    @Id
    private Long id;
 
    private String firstName;
 
    private String lastName;
 
    private static AtomicLong COUNTER = new AtomicLong(0L);
    
    @PersistenceConstructor
    public Customer() {
        this.id = COUNTER.incrementAndGet();
    }
 
    @Override
    public String toString() {
        return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);
    }
 
 
    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;
    }
}

通过扩展接口MongoRepository创建MongoDb存储库:

@RepositoryRestResource(collectionResourceRel = "customer", path = "customer")
public interface CustomerRepository extends MongoRepository<Customer, String> {
    List<Customer> findByLastName(@Param("name") String name);
}

在上面的代码中,我们定义了一个自定义方法,用于按姓氏查找列表客户。

打开application.properties来配置MongoDB:

spring.data.mongodb.database=restapi
spring.data.mongodb.port=27017

运行MongoDB服务器。然后运行Spring Boot项目。

欢迎大家加入粉丝群:963944895,群内免费分享Spring框架、Mybatis框架SpringBoot框架、SpringMVC框架、SpringCloud微服务、Dubbo框架、Redis缓存、RabbitMq消息、JVM调优、Tomcat容器、MySQL数据库教学视频及架构学习思维导图

写在最后:

既然看到这里了,觉得笔者写的还不错的就点个赞,加个关注呗!点关注,不迷路,持续更新!!!

    原文作者:Java高级架构狮
    原文地址: https://www.jianshu.com/p/6a7a5e499445
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞