Spring Data模块提供了各种模块,以统一的方式处理各种类型的数据源,如RDBMS,NOSQL存储等。 在我以前的文章SpringMVC4 + Spring Data JPA +使用JavaConfig的SpringSecurity配置中,我已经解释了如何使用JavaConfig配置Spring Data JPA。
现在,在这篇文章中,让我们看看如何使用Spring Data JPA存储库以及如何使用Spring Data REST将JPA实体导出为REST端点。
首先,让我们在pom.xml中配置spring-data-jpa和spring-data-rest-webmvc依赖项。
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.5.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
确保正确配置了最新发布的版本,否则将遇到以下错误:
java.lang.ClassNotFoundException: org.springframework.data.mapping.SimplePropertyHandler
创建JPA实体。
@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。 观察到我们已经将RepositoryRestMvcConfiguration.class添加到getServletConfigClasses()方法中。 RepositoryRestMvcConfiguration是一个繁重的工作,它寻找Spring Data Repository并将其导出为REST端点。
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
{
@Override
protected Class<?>[] getRootConfigClasses()
{
return new Class<?>[] { AppConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses()
{
return new Class<?>[] { WebMvcConfig.class, RepositoryRestMvcConfiguration.class };
}
@Override
protected String[] getServletMappings()
{
return new String[] { "/rest/*" };
}
@Override
protected Filter[] getServletFilters() {
return new Filter[]{
new OpenEntityManagerInViewFilter()
};
}
}
为JPA实体创建Spring Data JPA存储库。
public interface UserRepository extends JpaRepository<User, Integer>
{
}
public interface RoleRepository extends JpaRepository<Role, Integer>
{
}
public interface ContactRepository extends JpaRepository<Contact, Integer>
{
}
而已。 Spring Data REST将负责其余的工作。
您可以使用spring Rest Shell https://github.com/spring-projects/rest-shell或Chrome的Postman插件来测试导出的REST服务。
D:\rest-shell-1.2.1.RELEASE\bin>rest-shell
http://localhost:8080:>
现在我们可以使用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/>list
rel 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}
注意:当DispatcherServlet url映射到“ /”时,rest-shell似乎存在问题,并且它发出的list list命令以“未找到资源”作为响应。
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中找到源代码
- 有关Spring Rest Shell的更多信息: https : //github.com/spring-projects/rest-shell