如何构建SpringBoot MongoDb RestfulApi? - groko

19-01-29 banq
                   

打开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项目。

GET请求:localhost:8080

源码:SpringBootMongoDbRestApi