Статьи

Экспорт репозиториев Spring Data JPA в качестве REST-сервисов с использованием Spring Data REST

Модули Spring Data предоставляют различные модули для унифицированной работы с различными типами источников данных, такими как СУБД, хранилища NOSQL и т. Д. В моей предыдущей статье SpringMVC4 + Spring Data JPA + настройка SpringSecurity с использованием JavaConfig я объяснил, как настроить Spring Data JPA с использованием JavaConfig.

Теперь в этом посте давайте посмотрим, как мы можем использовать репозитории Spring Data JPA и экспортировать объекты JPA в качестве конечных точек REST, используя Spring Data REST.

Сначала давайте настроим зависимости spring-data-jpa и spring-data-rest-webmvc в нашем файле pom.xml.

01
02
03
04
05
06
07
08
09
10
11
<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>

Убедитесь, что последние выпущенные версии настроены правильно, иначе вы столкнетесь со следующей ошибкой:

1
java.lang.ClassNotFoundException: org.springframework.data.mapping.SimplePropertyHandler

Создать сущности JPA.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
@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
     
}

Настройте DispatcherServlet с помощью AbstractAnnotationConfigDispatcherServletInitializer . Обратите внимание, что мы добавили RepositoryRestMvcConfiguration.class в метод getServletConfigClasses () . RepositoryRestMvcConfiguration — это тот, который выполняет тяжелую работу по поиску репозиториев данных Spring и их экспорту в качестве конечных точек REST.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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()
       };
    }
}

Создание репозиториев Spring Data JPA для объектов JPA.

01
02
03
04
05
06
07
08
09
10
11
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 Addon для тестирования экспортированных REST-сервисов.

1
2
D:\rest-shell-1.2.1.RELEASE\bin>rest-shell
http://localhost:8080:>

Теперь мы можем изменить baseUri с помощью команды baseUri следующим образом:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
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}

Примечание. Кажется, есть проблема с rest-shell, когда URL-адрес DispatcherServlet сопоставлен с «/», и на команду list list он отвечает «Ресурсы не найдены».

http: // localhost: 8080 / spring-data-rest-demo / rest /> получить пользователей /

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
{
    "_links": {
        "self": {
            "href": "http://localhost:8080/spring-data-rest-demo/rest/users/{?page,size,sort}",
            "templated": true
        },
        "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
    }
}