javascript
Spring Data REST的实际应用
什么是春天數據休息?
spring-data-rest是spring-data項目的新增功能,它是一個框架,可幫助您將實體直接作為RESTful Web服務端點公開。 與rails,grails或roo不同,它不會生成任何實現此目標的代碼。 spring data-rest支持JPA,MongoDB,JSR-303驗證, HAL等。 它確實具有創新性,可讓您在幾分鐘內設置RESTful Web服務。 在此示例中,我將簡要概述spring-data-rest的功能。
初始配置
我將使用新的Servlet 3 Java Web Configuration而不是古老的web.xml。 這里沒什么特別的。
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {@Overrideprotected Class<?>[] getRootConfigClasses() {return new Class<?>[]{AppConfiguration.class};}@Overrideprotected Class<?>[] getServletConfigClasses() {return new Class[]{WebConfiguration.class};}@Overrideprotected String[] getServletMappings() {return new String[]{"/"};} }GitHub上的WebAppInitializer.java
我正在將hibernate初始化為AppConfiguration類中的數據庫抽象層。 我使用的是嵌入式數據庫( hsql ),因為我想使此演示文稿保持簡單愚蠢。 不過,這里沒有什么特別的。
@Configuration @EnableJpaRepositories @EnableTransactionManagement public class AppConfiguration {@Beanpublic DataSource dataSource() {EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();return builder.setType(EmbeddedDatabaseType.HSQL).build();}@Beanpublic LocalContainerEntityManagerFactoryBean entityManagerFactory() {HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();vendorAdapter.setDatabase(Database.HSQL);vendorAdapter.setGenerateDdl(true);LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();factory.setJpaVendorAdapter(vendorAdapter);factory.setPackagesToScan(getClass().getPackage().getName());factory.setDataSource(dataSource());return factory;}@Beanpublic PlatformTransactionManager transactionManager() {return new JpaTransactionManager();} }github上的AppConfiguration.java
現在到應用程序servlet配置: WebConfiguration
@Configuration public class WebConfiguration extends RepositoryRestMvcConfiguration { }github上的WebConfiguration.java
哦,那有點短吧? 完整的安裝程序不需要一行代碼。 這是約定優于配置范式的一個非常好的應用。 現在,我們可以開始創建spring-data-jpa存儲庫,因為它們將自動顯示為RESTful資源。 而且,如果需要,我們仍然可以將自定義配置添加到WebConfiguration類。
初始化真的很簡單。 我們不必編寫任何特殊的代碼。 我們唯一要做的就是建立數據庫連接和休眠,這顯然是不可避免的。 現在,我們已經設置了“ REST Servlet”和持久性,讓我們從模型開始進入應用程序本身。
該模型
我將僅創建兩個相關的實體,使其保持非常簡單的狀態。
GitHub上的Book.java
@Entity public class Author {@Id@GeneratedValue(strategy = GenerationType.SEQUENCE)private Integer id;private String name;@ManyToMany(mappedBy = "authors")private List<Book> books;}github上的Author.java
為了最終使實體持久化并作為RESTful Web服務公開,我們需要spring-data存儲庫。 存儲庫基本上是DAO 。 它為我們的實體提供CRUD功能。 spring-data消除了創建此類存儲庫的大部分編程工作。 我們只需要定義一個空接口,spring-data即可完成其他所有工作。 盡管如此,由于其設計優于配置,因此易于定制。
實際倉庫
@RestResource(path = "books", rel = "books") public interface BookRepository extends PagingAndSortingRepository<Book, Long> { }GitHub上的BookRepository.java
@RestResource(path = "authors", rel = "authors") public interface AuthorRepository extends PagingAndSortingRepository<Author, Integer> { }GitHub上的AuthorRepository.java
同樣,幾乎不需要代碼。 甚至@RestResource注釋也可以被忽略。 但是,如果我這樣做了,路徑和rel將以我不想要的實體命名。 但是,包含多個子項的REST資源應命名為復數。
訪問結果
我們的RESTful Web服務現在可以部署了。 運行后,它將在根目錄上列出所有可用資源,因此您可以從那里導航。
獲取http:// localhost:8080 /
{"links" : [ {"rel" : "books","href" : "http://localhost:8080/books"}, {"rel" : "authors","href" : "http://localhost:8080/authors"} ],"content" : [ ] }精細! 現在讓我們創建一個作者和一本書。
POST http:// localhost:8080 / authors
{"name":"Uncle Bob"}響應
201 Created Location: http://localhost:8080/authors/1放置http:// localhost:8080 / books / 0132350882
{"title": "Clean Code","authors": [{"rel": "authors","href": "http://localhost:8080/authors/1"}] }響應
201 Created注意到我是如何使用PUT創建書的? 這是因為其ID是實際的isbn。 我必須告訴服務器要使用哪個isbn,因為他無法猜測。 我為作者使用了POST,因為他的ID只是自動生成的一個增量數字。 另外,我使用了一個鏈接來連接這本書( / books / 0132350882 )和作者( / authors / 1 )。 基本上,這就是超媒體的全部意義:鏈接用于實體之間的導航和關系。
現在,讓我們看看這本書是否是相應創建的。
GET http:// localhost:8080 / books
{"links" : [ ],"content" : [ {"links" : [ {"rel" : "books.Book.authors","href" : "http://localhost:8080/books/0132350882/authors"}, {"rel" : "self","href" : "http://localhost:8080/books/0132350882"} ],"title" : "Clean Code"} ],"page" : {"size" : 20,"totalElements" : 1,"totalPages" : 1,"number" : 1} }精細!
這是一個集成測試,將自動執行以下步驟。 它也可以在github的示例中找到。
public class BookApiIT {private final RestTemplate restTemplate = new RestTemplate();private final String authorsUrl = "http://localhost:8080/authors";private final String booksUrl = "http://localhost:8080/books";@Testpublic void testCreateBookWithAuthor() throws Exception {final URI authorUri = restTemplate.postForLocation(authorsUrl, sampleAuthor()); // create Authorfinal URI bookUri = new URI(booksUrl + "/" + sampleBookIsbn);restTemplate.put(bookUri, sampleBook(authorUri.toString())); // create Book linked to AuthorResource<Book> book = getBook(bookUri);assertNotNull(book);final URI authorsOfBookUri = new URI(book.getLink("books.Book.authors").getHref());Resource<List<Resource<Author>>> authors = getAuthors(authorsOfBookUri);assertNotNull(authors.getContent());assertFalse(authors.getContent().isEmpty()); // check if /books/0132350882/authors contains an author}private String sampleAuthor() {return "{\"name\":\"Robert C. Martin\"}";}private final String sampleBookIsbn = "0132350882";private String sampleBook(String authorUrl) {return "{\"title\":\"Clean Code\",\"authors\":[{\"rel\":\"authors\",\"href\":\"" + authorUrl + "\"}]}";}private Resource<Book> getBook(URI uri) {return restTemplate.exchange(uri, HttpMethod.GET, null, new ParameterizedTypeReference<Resource<Book>>() {}).getBody();}private Resource<List<Resource<Author>>> getAuthors(URI uri) {return restTemplate.exchange(uri, HttpMethod.GET, null, new ParameterizedTypeReference<Resource<List<Resource<Author>>>>() {}).getBody();} }GitHub上的BookApiIT.java
結論
我們已經創建了完整的RESTful Web服務,而無需花費很多代碼。 我們只是定義了實體和數據庫連接。 spring-data-rest表示,其他所有內容都只是樣板,我同意。
要手動使用Web服務,請考慮rest-shell 。 它是一個命令外殼,它使您的Web服務中的導航盡可能輕松有趣。 這是屏幕截圖:
完整的示例可以在我的github上找到 https://github.com/gregorriegler/babdev-spring/tree/master/spring-data-rest https://github.com/gregorriegler/babdev-spring
翻譯自: https://www.javacodegeeks.com/2013/08/spring-data-rest-in-action.html
總結
以上是生活随笔為你收集整理的Spring Data REST的实际应用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DDOS机器人(机器人ddos插件)
- 下一篇: Spring MVC:Ajax和JQue