如何構建SpringBoot MongoDb RestfulApi

weixin_34185560發表於2019-01-30

開啟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資料庫教學視訊及架構學習思維導圖

寫在最後:

既然看到這裡了,覺得筆者寫的還不錯的就點個贊,加個關注唄!點關注,不迷路,持續更新!!!

相關文章