javascript
使用Spring Data REST将Spring Data JPA存储库导出为REST服务
Spring Data模塊提供了各種模塊,以統(tǒng)一的方式處理各種類型的數(shù)據(jù)源,如RDBMS,NOSQL存儲(chǔ)等。 在我以前的文章SpringMVC4 + Spring Data JPA +使用JavaConfig的SpringSecurity配置中,我已經(jīng)解釋了如何使用JavaConfig配置Spring Data JPA。
現(xiàn)在,在這篇文章中,讓我們看看如何使用Spring Data JPA存儲(chǔ)庫(kù)以及如何使用Spring Data REST將JPA實(shí)體導(dǎo)出為REST端點(diǎn)。
首先,讓我們?cè)趐om.xml中配置spring-data-jpa和spring-data-rest-webmvc依賴項(xiàng)。
確保正確配置了最新發(fā)布的版本,否則將遇到以下錯(cuò)誤:
java.lang.ClassNotFoundException: org.springframework.data.mapping.SimplePropertyHandler創(chuàng)建JPA實(shí)體。
@Entity @Table(name = "USERS") public class User implements Serializable {private static final long serialVersionUID = 1L;@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "user_id")private Integer id;@Column(name = "username", nullable = false, unique = true, length = 50)private String userName;@Column(name = "password", nullable = false, length = 50)private String password;@Column(name = "firstname", nullable = false, length = 50)private String firstName;@Column(name = "lastname", length = 50)private String lastName;@Column(name = "email", nullable = false, unique = true, length = 50)private String email;@Temporal(TemporalType.DATE)private Date dob;private boolean enabled=true;@OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)@JoinColumn(name="user_id")private Set<Role> roles = new HashSet<>();@OneToMany(mappedBy = "user")private List<Contact> contacts = new ArrayList<>();//setters and getters}@Entity @Table(name = "ROLES") public class Role implements Serializable {private static final long serialVersionUID = 1L;@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "role_id")private Integer id;@Column(name="role_name",nullable=false)private String roleName;//setters and getters}@Entity @Table(name = "CONTACTS") public class Contact implements Serializable {private static final long serialVersionUID = 1L;@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "contact_id")private Integer id;@Column(name = "firstname", nullable = false, length = 50)private String firstName;@Column(name = "lastname", length = 50)private String lastName;@Column(name = "email", nullable = false, unique = true, length = 50)private String email;@Temporal(TemporalType.DATE)private Date dob;@ManyToOne@JoinColumn(name = "user_id")private User user;//setters and getters}使用AbstractAnnotationConfigDispatcherServletInitializer配置DispatcherServlet。 觀察到我們已經(jīng)將RepositoryRestMvcConfiguration.class添加到getServletConfigClasses()方法中。 RepositoryRestMvcConfiguration是一個(gè)繁重的工作,它尋找Spring Data Repository并將其導(dǎo)出為REST端點(diǎn)。
package com.sivalabs.springdatarest.web.config;import javax.servlet.Filter; import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;import com.sivalabs.springdatarest.config.AppConfig;public class SpringWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {@Overrideprotected Class<?>[] getRootConfigClasses(){return new Class<?>[] { AppConfig.class};}@Overrideprotected Class<?>[] getServletConfigClasses(){return new Class<?>[] { WebMvcConfig.class, RepositoryRestMvcConfiguration.class };}@Overrideprotected String[] getServletMappings(){ return new String[] { "/rest/*" };} @Overrideprotected Filter[] getServletFilters() {return new Filter[]{new OpenEntityManagerInViewFilter()};} }為JPA實(shí)體創(chuàng)建Spring Data JPA存儲(chǔ)庫(kù)。
public interface UserRepository extends JpaRepository<User, Integer> { }public interface RoleRepository extends JpaRepository<Role, Integer> { }public interface ContactRepository extends JpaRepository<Contact, Integer> { }而已。 Spring Data REST將負(fù)責(zé)其余的工作。
您可以使用spring Rest Shell https://github.com/spring-projects/rest-shell或Chrome的Postman插件來測(cè)試導(dǎo)出的REST服務(wù)。
D:\rest-shell-1.2.1.RELEASE\bin>rest-shell http://localhost:8080:>現(xiàn)在我們可以使用baseUri命令更改baseUri,如下所示:
http://localhost:8080:>baseUri http://localhost:8080/spring-data-rest-demo/rest/http://localhost:8080/spring-data-rest-demo/rest/>http://localhost:8080/spring-data-rest-demo/rest/>listrel ? ? ? ? href======================================================================================users ? ? ? http://localhost:8080/spring-data-rest-demo/rest/users{?page,size,sort}roles ? ? ? http://localhost:8080/spring-data-rest-demo/rest/roles{?page,size,sort}contacts ? ?http://localhost:8080/spring-data-rest-demo/rest/contacts{?page,size,sort}注意:當(dāng)DispatcherServlet url映射到“ /”時(shí),rest-shell似乎存在問題,并且它發(fā)出的list list命令以“未找到資源”作為響應(yīng)。
http:// localhost:8080 / spring-data-rest-demo / rest />獲取用戶/
{"_links": {"self": {"href": "http://localhost:8080/spring-data-rest-demo/rest/users/{?page,size,sort}","templated": true},"search": {"href": "http://localhost:8080/spring-data-rest-demo/rest/users/search"}},"_embedded": {"users": [{"userName": "admin","password": "admin","firstName": "Administrator","lastName": null,"email": "admin@gmail.com","dob": null,"enabled": true,"_links": {"self": {"href": "http://localhost:8080/spring-data-rest-demo/rest/users/1"},"roles": {"href": "http://localhost:8080/spring-data-rest-demo/rest/users/1/roles"},"contacts": {"href": "http://localhost:8080/spring-data-rest-demo/rest/users/1/contacts"}}},{"userName": "siva","password": "siva","firstName": "Siva","lastName": null,"email": "sivaprasadreddy.k@gmail.com","dob": null,"enabled": true,"_links": {"self": {"href": "http://localhost:8080/spring-data-rest-demo/rest/users/2"},"roles": {"href": "http://localhost:8080/spring-data-rest-demo/rest/users/2/roles"},"contacts": {"href": "http://localhost:8080/spring-data-rest-demo/rest/users/2/contacts"}}}]},"page": {"size": 20,"totalElements": 2,"totalPages": 1,"number": 0} }- 您可以在https://github.com/sivaprasadreddy/sivalabs-blog-samples-code/tree/master/spring-data-rest-demo中找到源代碼
- 有關(guān)Spring Rest Shell的更多信息: https : //github.com/spring-projects/rest-shell
翻譯自: https://www.javacodegeeks.com/2014/03/exporting-spring-data-jpa-repositories-as-rest-services-using-spring-data-rest.html
總結(jié)
以上是生活随笔為你收集整理的使用Spring Data REST将Spring Data JPA存储库导出为REST服务的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 什么叫现金管理类理财产品?
- 下一篇: 红帽JBoss BRMS和BPMS富客户