MongoDB开发入门

1. 背景介绍

本文将通过一个简单的demo演示如何使用DoytoQuery框架快速为一个具有如下结构的角色表创建一套RESTful服务。

在阅读本文之前,需要你已经:

  • 有Java开发基础

  • 掌握MongoDB

  • 熟悉Maven

  • 熟悉SpringBoot

本文示例代码请访问Github

2. 开始编码

2.1. 初始化工程

1. 在 Spring Initializer 上初始化工程,添加以下4个依赖:Lombok, Spring Web, Validation, HyperSQL Database

2. 引入DoytoQuery

<dependency>
    <groupId>win.doyto</groupId>
    <artifactId>doyto-query-mongodb</artifactId>
    <version>0.3.0-ALPHA</version>
</dependency>
<dependency>
    <groupId>win.doyto</groupId>
    <artifactId>doyto-query-web</artifactId>
    <version>0.3.0</version>
</dependency>
<dependency>
    <groupId>win.doyto</groupId>
    <artifactId>doyto-query-dialect</artifactId>
    <version>0.0.1-RELEASE</version>
</dependency>

3. 添加默认Web配置

DemoApplication需要继承win.doyto.query.web.WebMvcConfigurerAdapter

DemoApplication.java
package win.doyto.query.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import win.doyto.query.web.WebMvcConfigurerAdapter;

@SpringBootApplication
public class DemoApplication extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(DoytoQueryDemoApplication.class, args);
    }

}

2.2. 初始化数据

schema.sql
SET DATABASE SQL SYNTAX MYS TRUE;

drop table t_role if exists;
create table t_role
(
    id        bigint generated by default as identity (start with 1) primary key,
    role_name VARCHAR(100) not null,
    role_code VARCHAR(100) not null,
    valid     boolean DEFAULT TRUE
);

INSERT INTO t_role (role_name, role_code) VALUES ('admin', 'ADMIN');
INSERT INTO t_role (role_name, role_code) VALUES ('vip', 'VIP');
INSERT INTO t_role (role_name, role_code) VALUES ('vip2', 'VIP2');
INSERT INTO t_role (role_name, role_code) VALUES ('vip3', 'VIP3');
INSERT INTO t_role (role_name, role_code) VALUES ('guest', 'GUEST');

2.3. 创建业务类

  • Role实体类,用于映射表字段

RoleEntity.java
package win.doyto.query.demo.module.role;

import lombok.Getter;
import lombok.Setter;
import win.doyto.query.entity.AbstractPersistable;
import win.doyto.query.validation.CreateGroup;

import javax.persistence.Table;
import javax.validation.constraints.NotNull;

@Getter
@Setter
@Table(name = "t_role")
public class RoleEntity extends AbstractPersistable<Integer> {

    @NotNull(groups = CreateGroup.class)
    private String roleName;

    @NotNull(groups = CreateGroup.class)
    private String roleCode;

    private Boolean valid;
}
  • Role查询类,用于生成查询语句

RoleQuery.java
package win.doyto.query.demo.module.role;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import win.doyto.query.core.PageQuery;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
public class RoleQuery extends PageQuery {
    private String roleNameLike;
}
  • Role业务类,用于提供CRUD功能和RESTful接口

RoleController.java
package win.doyto.query.demo.module.role;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import win.doyto.query.web.controller.AbstractEIQController;

@RestController
@RequestMapping("role")
public class RoleController extends AbstractEIQController<RoleEntity, Integer, RoleQuery> {
}

2.4. 启动工程进行验证

只需以上三个类就完成了整个RESTful服务的开发,接下来我们一起验证一下效果。

将org.springframework.web.servlet.mvc.method.annotation包的日志等级设置为trace,启动DemoApplication,可以看到/role/路径下已经有GET, PUT, PATCH等方法了:

s.w.s.m.m.a.RequestMappingHandlerMapping : 
	w.d.q.d.m.r.RoleController:
	{POST [/role]}: add(List)
	{PUT [/role/{id}]}: update(Serializable,Object)
	{GET [/role]}: paging(PageQuery)
	{GET [/role/{id}]}: getById(Serializable)
	{DELETE [/role/{id}]}: deleteById(Serializable)
	{PATCH [/role/{id}]}: patch(Serializable,Object)

然后通过curl访问一下分页查询接口:

curl 'http://localhost:8080/role/?roleNameLike=vip&pageNumber=1&pageSize=2&sort=id,desc'
{
  "code": 0,
  "message": "ok",
  "data": {
    "list": [
      {
        "id": 2,
        "roleName": "vip",
        "roleCode": "VIP",
        "valid": true
      }
    ],
    "total": 3
  },
  "success": true
}

可以看到我们使用roleNameLike=vip过滤出3条数据[id=2,3,4],再根据id倒序排列并通过pageNumber=1和pageSize=2查询出了第二页id为2的记录。

更多查询字段的用法请参考查询对象字段后缀汇总

再通过单元测试来验证一下:

@Test
@Rollback
void patchRole() throws Exception {
    RequestBuilder requestBuilder = patch("/role/2")
        .content("{\"roleName\":\"new role\"}")
        .contentType(MediaType.APPLICATION_JSON);
    performAndExpectSuccess(requestBuilder);
    performAndExpectSuccess(get("/role/2"))
            .andExpect(jsonPath("$.data.roleName").value("new role"))
    ;
}

完整的测试用例请查看这里

3. 小结

在这篇教程中,我们只编写了三个业务类就完成了t_role表RESTful服务的开发。其中RoleEntity对象作为数据的载体负责对表数据进行存取,RoleQuery对象作为查询参数的载体负责对查询的数据进行过滤,而RoleController负责提供web接口用于表的访问。另外,通过在RoleQuery类里定义一个字段roleNameLike就完成了对roleName的模糊查询,是不是很神奇?

这只是DoytoQuery功能的冰山一角,更多用法请继续查看后续章节!

最后更新于