spring-data-rest的魔力 10分鐘實現增刪改查

近日發現了spring-data-rest項目,因而建立這個spring-data-rest-glance來體驗一下。java

本例使用springboot,並使用了 spring-data-rest 和 spring-data-jpagit

此兩者結合:真的能夠實現10分鐘建立一個rest應用,下面開始演示spring-data-rest+spring-data-rest的魔力
本例假設你已經熟悉或者瞭解 springboot,spring-data-jpagithub

建立項目

咱們先建立一個springboot項目,能夠經過 start.spring.io 或者在idea裏邊new module --> spring Initializer 的方式。spring

建立好項目以後,咱們的依賴配置是這樣的:數據庫

<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數據庫的依賴。json

咱們建立一個person表,並建立personentityrepository,讓repository繼承JpaRepositoryapi

關鍵的來了:@RepositoryRestResource(collectionResourceRel = "person", path = "person")
咱們給repository加上一個@RepositoryRestResource註解,咱們來啓動項目,看看此註解的魔力。瀏覽器

啓動項目

訪問:htttp://localhost:8000/person 獲得的結果以下:tomcat

{
    "_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 模塊系統和反應流

相關文章
相關標籤/搜索