0% found this document useful (0 votes)
130 views86 pages

Spring MVC

Spring MVC

Uploaded by

TomasVileikis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views86 pages

Spring MVC

Spring MVC

Uploaded by

TomasVileikis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

Spring Data REST Reference Guide [Link]

1 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

GET

HEAD

POST

HEAD

PUT

PATCH

DELETE

GET

PUT

POST

DELETE

GET

HEAD

GET

HEAD

2 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

ETag If-Match If-None-Match

If-Modified-Since

ApplicationListener

@Pre @Post

3 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

rel

RepositoryRestHandlerMapping

ResourceProcessor

ObjectMapper

4 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

5 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

<dependencyManagement />

XML
<dependencyManagement>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-data-releasetrain</artifactId>
<version>Moore-SR6</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>

Moore-SR6

${name}-${release}

BUILD-SNAPSHOT

M1 M2

RC1 RC2

RELEASE

SR1 SR2

<dependencies />

XML
<dependencies>
<dependency>
<groupId>[Link]</groupId>

6 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependencies>

[Link]

7 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

GROOVY
dependencies {
...
compile("[Link]:spring-boot-starter-data-rest")
...
}

XML
<dependencies>
...
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
...
</dependencies>

8 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

spring-data-rest-webmvc

GROOVY
dependencies {
… other project dependencies
compile("[Link]:spring-data-rest-webmvc:[Link]")
}

spring-data-rest-webmvc

XML
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>[Link]</version>
</dependency>

RepositoryRestMvcConfiguration

9 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

@SpringBootApplication @EnableAutoConfiguration

RepositoryRestConfigurer
RepositoryRestConfigurerAdapter configure…

RepositoryDetectionStrategy
RepositoryDiscoveryStrategies

DEFAULT exported
@(Repository)RestResource

ALL

10 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

ANNOTATION @(Repository)RestResource
exported false

VISIBILITY

[Link]

PROPERTIES
[Link]=/api

JAVA
@Configuration
class CustomRestMvcConfiguration {

@Bean
public RepositoryRestConfigurer repositoryRestConfigurer() {

return new RepositoryRestConfigurerAdapter() {

@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config)
[Link]("/api");
}
};
}
}

RepositoryRestConfigurer

JAVA
@Component

11 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

public class CustomizedRestMvcConfiguration extends RepositoryRestConfigurerAdapter {

@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
[Link]("/api");
}
}

/api

basePath

defaultPageS
ize

maxPageSize

pageParamNam
e

limitParamNa
me

sortParamNam
e

defaultMedia
Type

returnBodyOn
Create

12 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

returnBodyOn
Update

13 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

public interface OrderRepository extends CrudRepository<Order, Long> { }

/orders

/orders/{id}

CrudRepository

CrudRepository

    @RestResource(exported
= false)    

14 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

200 OK GET

201 Created POST PUT

204 No Content PUT PATCH DELETE

[Link]
PUT 200 OK 201 Created
PUT

[Link]
[Link]) null

GET

curl -v [Link]

< HTTP/1.1 200 OK


< Content-Type: application/hal+json

15 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

{ "_links" : {
"orders" : {
"href" : "[Link]
},
"profile" : {
"href" : "[Link]
}
}
}

profile

@RepositoryRestResource

GET POST 405 Method


Not Allowed

GET

findAll(…)

findAll(Pageable)

16 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

findAll(Sort)

findAll()

page

size

sort ($propertyname,)+[asc|desc]

GET

405 Method Not Allowed findAll(…)


@RestResource(exported = false)

GET

application/hal+json

application/json

GET

search

HEAD

HEAD

17 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

findAll(Pageable)

findAll(Sort)

findAll()

POST

POST

save(…)

POST

405 Method Not Allowed save(…)


@RestResource(exported = false)

POST

18 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

GET PUT PATCH DELETE


“ ”

GET

findById(…)

GET

405 Method Not Allowed findOne(…)


@RestResource(exported = false)

GET

@RestResource

19 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

HEAD

HEAD

findById(…)

PUT

PUT

save(…)

PUT

405 Method Not Allowed save(…)


@RestResource(exported = false)

PUT

20 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

PATCH

PATCH PUT

save(…)

PATCH

405 Method Not Allowed save(…)


@RestResource(exported = false)

PATCH

DELETE

DELETE

21 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

delete(T)

delete(ID)

delete(Iterable)

DELETE

405 Method Not Allowed delete(…)


@RestResource(exported = false)

@RestResource

GET

GET

GET

22 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

PUT

PUT

PUT

400 Bad Request

PUT

POST

POST

POST

DELETE

DELETE

POST

405 Method Not Allowed

23 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

@RestResource

GET

GET

GET

GET

HEAD

HEAD

24 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

GET

GET

GET

page

size

sort ($propertyname,)+[asc|desc]

GET

application/hal+json

application/json

HEAD

HEAD

25 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

PagingAndSortingRepository<T, ID>
size

[Link]

Pageable Page List


/people/search/nameStartsWith

JAVA
@RestResource(path = "nameStartsWith", rel = "nameStartsWith")
public Page findByNameStartsWith(@Param("name") String name, Pageable p);

Page

prev next
prev next

26 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

curl localhost:8080/people?size=5

JAVASCRIPT
{
"_links" : {
"self" : {
"href" : "[Link] 1
"templated" : true
},
"next" : {
"href" : "[Link] 2
"templated" : true
}
},
"_embedded" : {
... data ...
},
"page" : { 3
"size" : 5,
"totalElements" : 50,
"totalPages" : 10,
"number" : 0
}
}

_links

1 self

2 next

curl &

self next size


page sort

27 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

next

$ curl "[Link]

JAVASCRIPT
{
"_links" : {
"self" : {
"href" : "[Link]
"templated" : true
},
"next" : {
"href" : "[Link] 1
"templated" : true
},
"prev" : {
"href" : "[Link] 2
"templated" : true
}
},
"_embedded" : {
... data ...
},
"page" : {
"size" : 5,
"totalElements" : 50,
"totalPages" : 10,
"number" : 1 3
}
}

next
1
self

2 prev

28 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

next

sort

, asc desc
findByNameStartsWith PersonRepository
Person “ ”
name

curl -v "[Link]

sort=PROPERTY
Pageable

Accept

29 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

ObjectMapper

JAVA
@Entity
public class MyEntity {
@OneToMany
private List<MyInterface> interfaces;
}

Module

30 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

ObjectMapper
configureJacksonObjectMapper ObjectMapper
PersistentEntity

JAVA
@Override
protected void configureJacksonObjectMapper(ObjectMapper objectMapper) {
[Link](new SimpleModule("MyCustomModule") {
@Override
public void setupModule(SetupContext context) {
[Link](
new SimpleAbstractTypeResolver().addMapping([Link],
[Link])
);
}
});
}

SetupContext Module
Module

ObjectMapper

setupModule

JAVA
@Override
public void setupModule(SetupContext context) {
SimpleSerializers serializers = new SimpleSerializers();
SimpleDeserializers deserializers = new SimpleDeserializers();

[Link]([Link], new MyEntitySerializer());


[Link]([Link], new MyEntityDeserializer());

[Link](serializers);
[Link](deserializers);
}

31 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

JAVA
@Entity
public class Person {

@Id @GeneratedValue
private Long id;
private String firstName, lastName;

@OneToOne
private Address address;

}

Person

id

firstName lastName

address

JAVA
interface PersonRepository extends CrudRepository<Person, Long> {}

32 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

firstName lastName
address Address

JAVA
interface AddressRepository extends CrudRepository<Address, Long> {}

Person address
Address “ ”

JAVASCRIPT
{
"firstName" : "Frodo",
"lastName" : "Baggins",
"_links" : {
"self" : {
"href" : "[Link]
},
"address" : {
"href" : "[Link]
}
}
}

Address
Person

JAVASCRIPT
{
"firstName" : "Frodo",
"lastName" : "Baggins",
"address" : {
"street": "Bag End",
"state": "The Shire",
"country": "Middle Earth"
},
"_links" : {
"self" : {
"href" : "[Link]
}
}

33 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

address
id

JAVA
@Projection(name = "noAddresses", types = { [Link] }) 1
interface NoAddresses { 2

String getFirstName(); 3

String getLastName(); 4
}

@Projection name
1 types
Person

3 firstName

4 lastName

NoAddresses firstName lastName


Address

JAVASCRIPT
{
"firstName" : "Frodo",
"lastName" : "Baggins",
"_links" : {
"self" : {
"href" : "[Link] 1
"templated" : true 2
},
"address" : {
"href" : "[Link]

34 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

}
}
}

1 {?projection}

2 self

[Link]
/1?projection=noAddresses

projection
@Projection(name = "noAddress")

@Projection

[Link]().addProjection(…)

@Projection

profile
Person
/alps/persons Person

35 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

GET

JAVASCRIPT
{ …
"id" : "get-person", 1
"name" : "person",
"type" : "SAFE",
"rt" : "#person-representation",
"descriptors" : [ {
"name" : "projection", 2
"doc" : {
"value" : "The projection that shall be applied when rendering the response. Acceptable values
"format" : "TEXT"
},
"type" : "SEMANTIC",
"descriptors" : [ {
"name" : "noAddresses", 3
"type" : "SEMANTIC",
"descriptors" : [ {
"name" : "firstName", 4
"type" : "SEMANTIC"
}, {
"name" : "lastName", 4
"type" : "SEMANTIC"
} ]
} ]
} ]
},

1 GET Person

2 projection

3 noAddresses

4 firstName lastName

36 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

@Projection

[Link]().addProjection(…)

@JsonIgnore

JAVA
@Entity
public class User {

@Id @GeneratedValue
private Long id;
private String name;

@JsonIgnore private String password; 1

private String[] roles;


@JsonIgnore password
1

User
UserRepository password

@JsonIgnore password

@JsonIgnore

37 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

JAVA
@Projection(name = "passwords", types = { [Link] })
interface PasswordProjection {

String getPassword();
}

@JsonIgnore
[Link]

JAVA
@Entity
public class Person {

...
private String firstName;
private String lastName;

...
}

38 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

JAVA
@Projection(name = "virtual", types = { [Link] })
public interface VirtualProjection {

@Value("#{[Link]} #{[Link]}") 1
String getFullName();

@Value
1 firstName lastName
fullName

PersonRepository

JAVA
@RepositoryRestResource(excerptProjection = [Link])
interface PersonRepository extends CrudRepository<Person, Long> {}

NoAddresses
Person

39 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

Person Address
address

GET

JAVA
@Projection(name = "inlineAddress", types = { [Link] }) 1
interface InlineAddress {

String getFirstName();

String getLastName();

Address getAddress(); 2
}

1 inlineAddress

getAddress Address
2

PersonRepository

JAVA
@RepositoryRestResource(excerptProjection = [Link])
interface PersonRepository extends CrudRepository<Person, Long> {}

JAVASCRIPT
{
"firstName" : "Frodo",
"lastName" : "Baggins",
"address" : { 1
"street": "Bag End",
"state": "The Shire",

40 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

"country": "Middle Earth"


},
"_links" : {
"self" : {
"href" : "[Link]
},
"address" : { 2
"href" : "[Link]
}
}
}

1 address

Address
2

@RepositoryRestResource(excerptProjection=…)

ETag If-Match If-None-Match

ETag

41 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

JAVA
public class Sample {

@Version Long version; 1

Sample(Long version) {
[Link] = version;
}
}

@Version
1 [Link]

ETag

PUT PATCH DELETE If-Match

curl -v -X PATCH -H 'If-Match: <value of previous ETag>' ...

ETag If-Match

ETag
ETag
If-Match
412 Precondition Failed

“ ”

ETag

42 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

If-None-Match If-None-
Match

curl -v -H 'If-None-Match: <value of previous etag>' ...

GET If-None-
Match GET
304 Not
Modified “

ETag @Entity
@Document
@Version ETag

If-Modified-Since

If-Modified-Since

JAVA
@Document
public class Receipt {

public @Id String id;


public @Version Long version;
public @LastModifiedDate Date date; 1

public String saleItem;


public BigDecimal amount;

43 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

@LastModifiedDate
1 DateTime Date
Calendar long Long

Last-Modified

Last-Modified: Wed, 24 Jun 2015 [Link] GMT

curl -H "If-Modified-Since: Wed, 24 Jun 2015 [Link] GMT" ...

Last-Modified
304 Not Modified

ETag If-Match If-None-Match

data-*
data-etag

44 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

Last-Modified data-last-modified

self data-uri
data-self

PUT PATCH DELETE If-Match 412


Precondition Failed

GET If-None-Match If-Modified-Since 304


Not Modified

ETag Last-Modified

Validator

Validator

Person
Validator<Person> ApplicationContext
beforeCreatePersonValidator beforeCreate

45 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

RepositoryRestConfigurer
RepositoryRestConfigurerAdapter configureValidatingRepositoryEventListener
addValidator ValidatingRepositoryEventListener

JAVA
@Override
protected void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener v)
[Link]("beforeSave", new BeforeSaveValidator());
}

BeforeCreateEvent

AfterCreateEvent

BeforeSaveEvent

AfterSaveEvent

BeforeLinkSaveEvent

AfterLinkSaveEvent

BeforeDeleteEvent

AfterDeleteEvent

ApplicationListener

46 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

JAVA
public class BeforeSaveEventListener extends AbstractRepositoryEventListener {

@Override
public void onBeforeSave(Object entity) {
... logic to handle inspecting the entity before the Repository saves it
}

@Override
public void onAfterDelete(Object entity) {
... send a message that this entity has been deleted
}
}

@RepositoryEventHandler
BeanPostProcessor

BeanPostProcessor

BeforeSaveEvent

JAVA
@RepositoryEventHandler 1
public class PersonEventHandler {

@HandleBeforeSave
public void handlePersonSave(Person p) {
// … you can now deal with Person in a type-safe way
}

@HandleBeforeSave
public void handleProfileSave(Profile p) {
// … you can now deal with Profile in a type-safe way
}
}

47 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

1
@RepositoryEventHandler([Link])

@Component
@SpringBootApplication @ComponentScan
ApplicationContext
BeanPostProcessor RepositoryRestMvcConfiguration

Person

JAVA
@Configuration
public class RepositoryConfiguration {

@Bean
PersonEventHandler personEventHandler() {
return new PersonEventHandler();
}
}

48 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

LinkBuilder linkTo() slash()

RepositoryEntityLinks

JAVA
public class MyWebApp {

private RepositoryEntityLinks entityLinks;

@Autowired
public MyWebApp(RepositoryEntityLinks entityLinks) {
[Link] = entityLinks;
}
}

[Link](Person
.class) Person

[Link]([Link]
ss, 1)

[Link]([Link]
s, new PageRequest(…))

49 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

[Link](Person.c
lass)

[Link]([Link] rel
ss, "findByLastName")

RepositoryEntityLinks linkFor(Class<?> type)


LinkBuilder

50 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

persons addresses

JAVASCRIPT
{
"_links" : {
"persons" : {
"href" : "[Link]
},
"addresses" : {
"href" : "[Link]
},
"profile" : {
"href" : "[Link]
}
}
}

localhost:8080/profile

JAVASCRIPT
{
"_links" : {
"self" : {
"href" : "[Link]
},
"persons" : {
"href" : "[Link]
},
"addresses" : {
"href" : "[Link]
}
}
}

profile
/profile

51 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

/profile/persons Person

JAVASCRIPT
{
"version" : "1.0",
"descriptors" : [ {
"id" : "person-representation", 1
"descriptors" : [ {
"name" : "firstName",
"type" : "SEMANTIC"
}, {
"name" : "lastName",
"type" : "SEMANTIC"
}, {
"name" : "id",
"type" : "SEMANTIC"
}, {
"name" : "address",
"type" : "SAFE",
"rt" : "[Link]
} ]
}, {
"id" : "create-persons", 2
"name" : "persons", 3
"type" : "UNSAFE", 4
"rt" : "#person-representation" 5
}, {
"id" : "get-persons",
"name" : "persons",
"type" : "SAFE",
"rt" : "#person-representation"
}, {
"id" : "delete-person",
"name" : "person",
"type" : "IDEMPOTENT",
"rt" : "#person-representation"
}, {
"id" : "patch-person",
"name" : "person",
"type" : "UNSAFE",
"rt" : "#person-representation"
}, {
"id" : "update-person",
"name" : "person",
"type" : "IDEMPOTENT",
"rt" : "#person-representation"
}, {
"id" : "get-person",
"name" : "person",
"type" : "SAFE",
"rt" : "#person-representation"
} ]

52 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

Person #person-
1
representation

2 Person

name persons
3
person

4 type UNSAFE

application/alps+json
application/hal+json

profile _links

JAVASCRIPT
{
"_links" : {
"self" : {
"href" : "[Link] 1
},
... other links ...
"profile" : {
"href" : "[Link] 2
}
},
...
}

1 Person

profile Accept
application/alps+json

53 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

[Link] [Link]

GET HEAD

PUT DELETE

POST

SEMANTIC address GET


SAFE

inlineAddress noAddresses
“ ”

get-persons

JAVASCRIPT
...
{
"id" : "get-persons",
"name" : "persons",

54 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

"type" : "SAFE",
"rt" : "#person-representation",
"descriptors" : [ { 1
"name" : "projection",
"doc" : {
"value" : "The projection that shall be applied when rendering the response. Acceptable valu
"format" : "TEXT"
},
"type" : "SEMANTIC",
"descriptors" : [ {
"name" : "inlineAddress", 2
"type" : "SEMANTIC",
"descriptors" : [ {
"name" : "address",
"type" : "SEMANTIC"
}, {
"name" : "firstName",
"type" : "SEMANTIC"
}, {
"name" : "lastName",
"type" : "SEMANTIC"
} ]
}, {
"name" : "noAddresses", 3
"type" : "SEMANTIC",
"descriptors" : [ {
"name" : "firstName",
"type" : "SEMANTIC"
}, {
"name" : "lastName",
"type" : "SEMANTIC"
} ]
} ]
} ]
}
...

descriptors
1
projection

[Link] inLineAddress address


2 firstName lastName

3 noAddresses firstName lastName

55 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

rest-
[Link]

PROPERTIES
[Link]=A collection of people
[Link]=primary key used internally to store a person (not for RESTful usage)
[Link]=Person's first name
[Link]=Person's last name
[Link]=Person's address

[Link].* Person
person-representation

JAVASCRIPT
...
{
"id" : "person-representation",
"doc" : {
"value" : "A collection of people", 1
"format" : "TEXT"
},
"descriptors" : [ {
"name" : "firstName",
"doc" : {
"value" : "Person's first name", 2
"format" : "TEXT"
},
"type" : "SEMANTIC"
}, {
"name" : "lastName",
"doc" : {
"value" : "Person's last name", 3
"format" : "TEXT"
},
"type" : "SEMANTIC"
}, {
"name" : "id",
"doc" : {
"value" : "primary key used internally to store a person (not for RESTful usage)"
"format" : "TEXT"
},
"type" : "SEMANTIC"
}, {
"name" : "address",
"doc" : {

56 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

"value" : "Person's address", 5


"format" : "TEXT"
},
"type" : "SAFE",
"rt" : "[Link]
} ]
}
...

1 [Link]

2 [Link] firstName

3 [Link] lastName

[Link] id
4

5 [Link] address

doc

profile

57 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

JAVASCRIPT
{
"_links" : {
"self" : {
"href" : "[Link]
},
"persons" : {
"href" : "[Link]
},
"addresses" : {
"href" : "[Link]
}
}
}

Accept application/schema+json

curl -H 'Accept:application/schema+json' [Link]


/profile/persons

JAVASCRIPT
{
"title" : "[Link]", 1
"properties" : { 2
"firstName" : {
"readOnly" : false,
"type" : "string"
},
"lastName" : {
"readOnly" : false,
"type" : "string"
},
"siblings" : {
"readOnly" : false,
"type" : "string",
"format" : "uri"
},
"created" : {
"readOnly" : false,
"type" : "string",
"format" : "date-time"
},
"father" : {
"readOnly" : false,
"type" : "string",
"format" : "uri"
},

58 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

"weight" : {
"readOnly" : false,
"type" : "integer"
},
"height" : {
"readOnly" : false,
"type" : "integer"
}
},
"descriptors" : { },
"type" : "object",
"$schema" : "[Link]
}

profile _links

JAVASCRIPT
{
"_links" : {
"self" : {
"href" : "[Link] 1
},
... other links ...
"profile" : {
"href" : "[Link] 2
}
},
...
}

1 Person

profile Accept
application/schema+json

59 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

@Pre @Post

JAVA
@PreAuthorize("hasRole('ROLE_USER')") 1
public interface PreAuthorizedOrderRepository extends CrudRepository<Order, UUID> {

@PreAuthorize("hasRole('ROLE_ADMIN')") 2
@Override
void deleteById(UUID aLong);

@PreAuthorize("hasRole('ROLE_ADMIN')")
@Override
void delete(Order order);

@PreAuthorize("hasRole('ROLE_ADMIN')")
@Override
void deleteAll(Iterable<? extends Order> orders);

@PreAuthorize("hasRole('ROLE_ADMIN')")
@Override
void deleteAll();
}

1 ROLE_USER

2
ROLE_ADMIN

60 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

CrudRepository

CrudRepository

@Secured

JAVA
@Secured("ROLE_USER") 1
@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface SecuredPersonRepository extends CrudRepository<Person, UUID> {

@Secured("ROLE_ADMIN") 2
@Override
void deleteById(UUID aLong);

@Secured("ROLE_ADMIN")
@Override
void delete(Person person);

@Secured("ROLE_ADMIN")
@Override
void deleteAll(Iterable<? extends Person> persons);

@Secured("ROLE_ADMIN")
@Override
void deleteAll();
}

61 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

2 ROLE_ADMIN

@PreAuthorize
@Secured

JAVA
@Configuration 1
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) 2
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 3
...
}

@EnableGlobalMethodSecurity
2 @Secured @Pre @Post

WebSecurityConfigurerAdapter
3

62 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

XML
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-data-rest-hal-browser</artifactId>
</dependency>
</dependencies>

GROOVY
dependencies {
compile '[Link]:spring-data-rest-hal-browser'
}

63 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

64 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

65 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

findOne(…)
RepositoryRestConfiguration

66 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

EntityLookup

User username
Optional<User> findByUsername(String username)

JAVA
@Component
public class SpringDataRestCustomization extends RepositoryRestConfigurer {

@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
[Link]()
.forRepository([Link])
.withIdMapping(User::getUsername)
.withLookup(UserRepository::findByUsername);
}
}

forRepository(…)

UserEntityLookup

JAVA
@Component
public class UserEntityLookup extends EntityLookupSupport<User> {

private final UserRepository repository;

public UserEntityLookup(UserRepository repository) {


[Link] = repository;
}

@Override

67 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

public Serializable getResourceIdentifier(User entity) {


return [Link]();
}

@Override
public Object lookupEntity(Serializable id) {
return [Link]([Link]());
}
}

getResourceIdentifier(…)

lookupEntity(…) UserRepository

RepositoryDetectionStrategy
RepositoryDetectionStrategies RepositoryRestConfiguration

ALL    

DEFAULT    
@RepositoryRestResource exported false

VISIBILITY    

ANNOTATED    
@RepositoryRestResource exported false

RepositoryDetectionStrategy

68 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

CrudRepository

delete(…) DELETE

@RestResource(exported = false)

save(…) POST PUT PATCH

[Link]()

JAVA
ExposureConfiguration config = [Link]();

[Link]([Link]).disablePutForCreation(); 1
[Link]((metadata, httpMethods) -> [Link]([Link])); 2

1 PUT

2 PATCH

CrudRepository

69 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

JAVA
interface PersonRepository extends CrudRepository<Person, Long> {}

[Link]
/persons/

@RestResource

JAVA
@RepositoryRestResource(path = "people")
interface PersonRepository extends CrudRepository<Person, Long> {}

[Link]
/people/

JAVA
interface PersonRepository extends CrudRepository<Person, Long> {

List<Person> findByName(String name);


}

[Link]
/findByName

search

@RestResource

70 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

JAVA
@RepositoryRestResource(path = "people")
interface PersonRepository extends CrudRepository<Person, Long> {

@RestResource(path = "names")
List<Person> findByName(String name);
}

[Link]
/search/names

rel

rel

[Link]
/persons/search

JAVASCRIPT
{
"_links" : {
"findByName" : {
"href" : "[Link]
}
}
}

rel rel @RestResource

JAVA
@RepositoryRestResource(path = "people")
interface PersonRepository extends CrudRepository<Person, Long> {

@RestResource(path = "names", rel = "names")


List<Person> findByName(String name);
}

71 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

JAVASCRIPT
{
"_links" : {
"names" : {
"href" : "[Link]
}
}
}

rel

rel

JAVA
@RepositoryRestResource(path = "people", rel = "people")
interface PersonRepository extends CrudRepository<Person, Long> {

@RestResource(path = "names", rel = "names")


List<Person> findByName(String name);
}

rel

JAVASCRIPT
{
"_links" : {
"people" : {
"href" : "[Link]
},

}
}

72 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

path = "people" href /persons /people

rel = "people" persons people

search
@RestResource

JAVASCRIPT
{
"_links" : {
"names" : {
"href" : "[Link]
}
}
}

path = "people"
/people

/people/search

path = "names" /people/search/names

rel = "names" findByNames names

password User

@RestResource exported = false

JAVA
@RepositoryRestResource(exported = false)

73 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

interface PersonRepository extends CrudRepository<Person, Long> {}

@RestResource(exported = false)

JAVA
@RepositoryRestResource(path = "people", rel = "people")
interface PersonRepository extends CrudRepository<Person, Long> {

@RestResource(exported = false)
List<Person> findByName(String name);
}

@RestResource(exported =
false)

JAVA
@Entity
public class Person {

@Id @GeneratedValue private Long id;

@OneToMany
@RestResource(exported = false)
private Map<String, Profile> profiles;
}

CrudRepository
@RestResource(exported = false)

74 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

CrudRepository

JAVA
@RepositoryRestResource(path = "people", rel = "people")
interface PersonRepository extends CrudRepository<Person, Long> {

@Override
@RestResource(exported = false)
void delete(Long id);

@Override
@RestResource(exported = false)
void delete(Person entity);
}

delete

delete

delete
exported = false

spring-boot-starter-data-rest

RepositoryRestController
[Link]

75 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

@Import

JAVA
import [Link];
import [Link];

@Configuration
@Import([Link])
public class MyApplicationConfiguration {


}

XML
<bean class="[Link]"/>

ApplicationContext

RepositoryRestHandlerMapping

RepositoryRestHandlerMapping

HandlerMapping

76 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

RepositoryRestController

HandlerMapping

HandlerMapping
null “ HandlerMapping

HandlerMapping order=(Ordered.LOWEST_PRECEDENCE -
100)

person
/person
people
/people /person

@RepositoryRestController @Controller
@RestController @RepositoryRestController
[Link]
/api
@RepositoryRestController

JAVA
@RepositoryRestController
public class ScannerController {

private final ScannerRepository repository;

@Autowired
public ScannerController(ScannerRepository repo) { 1
repository = repo;
}

@RequestMapping(method = GET, value = "/scanners/search/listProducers") 2


public @ResponseBody ResponseEntity<?> getProducers() {

77 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

List<String> producers = [Link](); 3

//
// do some intermediate processing, logging, etc. with the producers
//

Resources<String> resources = new Resources<String>(producers); 4

[Link](linkTo(methodOn([Link]).getProducers()).withSelfRel());

// add other links as needed

return [Link](resources); 6
}

Resources
4
Resource

5 self

ResponseEntity
6

Resources Resource
Resources<Resource<String>>
String

[Link]()
/scanners/search/listProducers

78 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

basePath
@BasePathAwareController @RepositoryRestResource

OpenEntityManagerInViewInterceptor

@Controller @RestController

Customer

ResourceProcessor

ResourceProcessor<>
ResourceProcessor<Resource<T>>
T

Person @Bean
ApplicationContext

JAVA
@Bean
public ResourceProcessor<Resource<Person>> personProcessor() {

79 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

return new ResourceProcessor<Resource<Person>>() {

@Override
public Resource<Person> process(Resource<Person> resource) {

[Link](new Link("[Link] "added-link"));


return resource;
}
};
}

[Link]

linkTo(…)

[Link](Link)
Resource

ResourceProcessor
Converter<Entity, Resource>
ConversionService
_links
@Entity
Repository

ConversionService ApplicationContext Converter<Entity,


Resource> Resource

80 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

ObjectMapper

ObjectMapper

ObjectMapper

JAVA
@Entity
public class MyEntity {

@OneToMany
private List<MyInterface> interfaces;
}

Module ApplicationContext
ObjectMapper
Module setupModule
TypeResolver

81 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

JAVA
public class MyCustomModule extends SimpleModule {

private MyCustomModule() {
super("MyCustomModule", new Version(1, 0, 0, "SNAPSHOT"));
}

@Override
public void setupModule(SetupContext context) {
[Link](
new SimpleAbstractTypeResolver().addMapping([Link],
[Link]));
}
}

SetupContext Module

ObjectMapper

setupModule

JAVA
public class MyCustomModule extends SimpleModule {

@Override
public void setupModule(SetupContext context) {

SimpleSerializers serializers = new SimpleSerializers();


SimpleDeserializers deserializers = new SimpleDeserializers();

[Link]([Link], new MyEntitySerializer());


[Link]([Link], new MyEntityDeserializer());

[Link](serializers);
[Link](deserializers);
}

82 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

@CrossOrigin
@CrossOrigin

JAVA
@CrossOrigin
interface PersonRepository extends CrudRepository<Person, Long> {}

PersonRepository
@CrossOrigin

JAVA
@CrossOrigin(origins = "[Link]
methods = { [Link], [Link], [Link] },
maxAge = 3600)
interface PersonRepository extends CrudRepository<Person, Long> {}

PersonRepository

83 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

GET POST DELETE

JAVA
@RepositoryRestController
public class PersonController {

@CrossOrigin(maxAge = 3600)
@RequestMapping(path = "/people/xml/{id}", method = [Link], produces = [Link]
public Person retrieve(@PathVariable Long id) {
// …
}
}

@RepositoryRestController @CrossOrigin

@CrossOrigin
GET HEAD POST

84 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

JAVA
@Component
public class SpringDataRestCustomization extends RepositoryRestConfigurerAdapter {

@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {

[Link]().addMapping("/person/**")
.allowedOrigins("[Link]
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}
}

85 of 86 4/14/2020, 11:41 AM
Spring Data REST Reference Guide [Link]

spring-data-examples/rest

86 of 86 4/14/2020, 11:41 AM

You might also like