zoukankan      html  css  js  c++  java
  • spring-data-rest的魔力 10分钟实现增删改查

    近日发现了spring-data-rest项目,于是创建这个spring-data-rest-glance来体验一下。

    本例使用springboot,并使用了 spring-data-rest 和 spring-data-jpa

    此二者结合:真的可以实现10分钟创建一个rest应用,下面开始演示spring-data-rest+spring-data-rest的魔力
    本例假设你已经熟悉或者了解 springboot,spring-data-jpa

    创建项目

    我们先创建一个springboot项目,可以通过 start.spring.io 或者在idea里边new module --> spring Initializer 的方式。

    创建好项目之后,我们的依赖配置是这样的:

        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.3.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-rest</artifactId>
            </dependency>
    
            <dependency>
                <groupId>com.h2database</groupId>
                <artifactId>h2</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    

    本例使用的是h2数据库,所以加了h2数据库的依赖。

    我们创建一个person表,并创建personentityrepository,让repository继承JpaRepository

    关键的来了:@RepositoryRestResource(collectionResourceRel = "person", path = "person")
    我们给repository加上一个@RepositoryRestResource注解,我们来启动项目,看看此注解的魔力。

    启动项目

    访问:htttp://localhost:8000/person 得到的结果如下:

    {
        "_embedded": {
            "person": []
        },
        "_links": {
            "self": {
                "href": "http://localhost:8000/person{?page,size,sort}",
                "templated": true
            },
            "profile": {
                "href": "http://localhost:8000/profile/person"
            },
            "search": {
                "href": "http://localhost:8000/person/search"
            }
        },
        "page": {
            "size": 20,
            "totalElements": 0,
            "totalPages": 0,
            "number": 0
        }
    }
    

    我们看到 person节点并无内容。同时请注意 _links 节点下的内容。我们下面将会用到它。

    添加person

    我们使用POST方式访问 http://localhost:8000/person 并提交如下 JSON 数据:

    {"firstName": "tomcat", "lastName": "cat"}
    

    如此,就完成了添加操作,你可以多添加几条数据试试。

    查看person 及 person 列表

    我们再次在浏览器中访问(GET) http://localhost:8000/person。得到的结果中,JSON数据和第一步中一样,person节点中不再是空的了。

    [
        {
            "firstName": "tomcat",
            "lastName": "cat",
            "_links": {
                "self": {
                    "href": "http://localhost:8000/person/1"
                },
                "person": {
                    "href": "http://localhost:8000/person/1"
                }
            }
        }
    ]
    

    我们可以继续多添加几条数据,方便下面展示查询。在添加多条信息之后,如果想查看某个person的详情,例如:http://localhost:8000/person/7

    {
        "firstName": "李",
        "lastName": "四",
        "_links": {
            "self": {
                "href": "http://localhost:8000/person/7"
            },
            "person": {
                "href": "http://localhost:8000/person/7"
            }
        }
    }
    

    条件查询

    假设我们需要根据用户名查询用户,我们在PersonRepository中添加一个方法findByLastName.
    托spring-data-jpa的福,我们只需要写这样的一行代码,然后什么都不用做,spring-data-jpa会解析findByLastName并应用到查询上。

    List<Person> findByLastName(@Param("name") String name);
    

    写好上面的代码之后,我们重启项目,访问http://localhost:8000/person/search结果如下:

    {
        "_links": {
            "findByLastName": {
                "href": "http://localhost:8000/person/search/findByLastName{?name}",
                "templated": true
            },
            "findByFirstName": {
                "href": "http://localhost:8000/person/search/findByFirstName{?name}",
                "templated": true
            },
            "self": {
                "href": "http://localhost:8000/person/search"
            }
        }
    }
    

    我们可以看到,这里已经列出了当前可用的search方法。我们访问:http://localhost:8000/person/search/findByLastName?name=cat

    {
        "person": [
            {
                "firstName": "tomcat",
                "lastName": "cat",
                "_links": {
                    "self": {
                        "href": "http://localhost:8000/person/1"
                    },
                    "person": {
                        "href": "http://localhost:8000/person/1"
                    }
                }
            },
            {
                "firstName": "tom",
                "lastName": "cat",
                "_links": {
                    "self": {
                        "href": "http://localhost:8000/person/2"
                    },
                    "person": {
                        "href": "http://localhost:8000/person/2"
                    }
                }
            }
        ]
    }
    

    我们可以看到,这里通过findByLastName?name=cat找到了两个人:tomcat cat 和 tom cat

    分页查询

    为了演示分页,我们先多添加几条用户数据。在第一步中展示的结果中,我们可以看到这样的一行数据:
    http://localhost:8000/person{?page,size,sort}
    这提示了我们分页的使用方法,我们来访问http://localhost:8000/person?page=2&size=3 试试,即:访问第2页数据,页大小是3。
    下面贴出 关键结果的节点:

    {
        "_embedded": {
            "person": [
                {
                    "firstName": "李",
                    "lastName": "四",
                    "_links": {
                        "self": {
                            "href": "http://localhost:8000/person/7"
                        },
                        "person": {
                            "href": "http://localhost:8000/person/7"
                        }
                    }
                },
                {
                    "firstName": "王",
                    "lastName": "五",
                    "_links": {
                        "self": {
                            "href": "http://localhost:8000/person/8"
                        },
                        "person": {
                            "href": "http://localhost:8000/person/8"
                        }
                    }
                }
            ]
        },
        "page": {
            "size": 3,
            "totalElements": 8,
            "totalPages": 3,
            "number": 2
        }
    }
    

    确实查到了数据,结果对不对呢?根据上面的从上面的结果看出,我们添加8条数据,页大小是3,所以:
    总页数 = 3 第一页 3条数据 第二页 3条数据 第三页 2条数据
    我们访问的是,http://localhost:8000/person?page=2&size=3page=2,但是实际上取的是2条数据——是第3页。那么页码其实是从0开始的对吗?
    我们继续访问 http://localhost:8000/person?page=0&size=3 http://localhost:8000/person?page=1&size=3
    可以发现,确实是如此,页码从0开始。any way

    controller 去哪里了

    到目前为止,我们只写了很少的代码,只写了DAO,但是却已经实现了增删改查resp api。我们甚至连 controller都没有写,就访问了这么多的rest url。
    我们只通过@RepositoryRestResource(collectionResourceRel = "person", path = "person")在 dao 中就能够把 /path路径暴露出来。
    边一切都有了,这就是spring-data-rest的魔力。

    自定义 spring-data-rest 魔力之外的controller可以吗

    当然可以了,上面我们所访问的 /person/* 的地址,是从dao中通过 @RepositoryRestResource 注解暴露出去的。
    那么现在我们就手写一个controller,访问路径也叫/person,即:@RequestMapping("/person")

    @Controller
    @RequestMapping("/person")
    public class PersonController {
    
    	@RequestMapping("/hello")
    	@ResponseBody
    	public String hello(){
    		return " Hello,welcome to the normal controller! ";
    	}
    
    }
    

    我们自己创建的controller访问路径也是,/person 还创建了一个自定义的 hello方法,这个/person 和dao里边暴露的/person
    能共存,并和谐相处吗?我们访问看看:http://localhost:8000/person/hello 我们在浏览器中可以看到:

    Hello,welcome to the normal controller!
    

    很完美,这里我们可以得出,我们能利用spring-data-rest + spring-data-jpa实现基本的增删改查api.
    我们只需要自己去写复杂的api就行了,简单的根本不用写,岂不是很快!

    总结

    至此,我们体验了一下 spring-data-rest。总有“刁民”说java开发很慢,代码太多了。多吗?不多啊,我们这里使用spring-data-jpa
    加上spring-data-rest,只写了很少的代码就实现了大部分基础的功能了。下次开发新项目,可以尝试使用 spring-data-rest加spring-data-jpa了。

    代码在这里

    推荐阅读
    探索Java9 模块系统和反应流
    Java8系列- 如何用Java8 Stream API找到心仪的女朋友
    Java8系列- 何用Java8 Stream API进行数据抽取与收集
    Spring Security 入门原理及实战
    SpringMVC是怎么工作的,SpringMVC的工作原理
    Mybatis Mapper接口是如何找到实现类的-源码分析
    小程序云开发:菜鸟也能全栈做产品
    CORS详解,CORS原理分析
    工作6年,失业19天
    alt 逃离沙漠公众号

  • 相关阅读:
    ASP.Net Core -- Logging
    ASP.Net Core -- 文件上传
    ASP.Net Core -- 依赖注入
    ASP.Net Core -- 领域模型与数据库架构保持同步
    Entity Framework Core -- 种子数据
    ASP.Net Core -- Environment TagHelper
    ASP.Net Core -- 为什么要使用TagHelper?
    dotnet ef 无法执行,因为找不到指定的命令或文件
    ASP.Net Core 3.x -- 中间件流程与路由体系
    ASP.Net Core -- View Components
  • 原文地址:https://www.cnblogs.com/demingblog/p/10599134.html
Copyright © 2011-2022 走看看