Issue
I have a Person.java
class that contain id,firstName,lastName:
According to the documentation, if I wish to have hateoas link, pagination and count, I should use a PersonResource
:
https://docs.spring.io/spring-hateoas/docs/current/reference/html/#fundamentals.resources
Is it the same thing as Person
?
How should I do for my id, has ResourceSupport
already have a getId()
method implemented.
Solution
The id of your domain object and the id of the REST resource are two completely different things.
As mentioned in the Spring HATEOAS API documentation, a Resource is a wrapper around a domain object that adds link to it. A Resource is a fundamental concept of REST. It's an object with a type, associated data, relationships to other resources, and a set of methods that operate on it.
Basically, its id is the URL you use to interact with the GET/PUT/POST/DELETE methods.
Wrapped into the resource (PersonResource), is your domain object (Person), a POJO with properties and getters/setters :
// simple definition of a Person Resource in Spring
public class PersonResource extends Resource<Person> {
public PersonResource(Person content, Link... links) {
super(content, links);
}
}
public class Person {
...
String name;
Integer age;
// getters/setters omitted for clarity
}
A REST API is generally used to access and update data stored in a database table (SQL) or collection (NoSQL). Such an entity has a unique id, that you map against the id property of your POJO:
public class Person {
@Id
String id;
String name;
Integer age;
// getters/setters omitted for clarity
}
By default, when you interrogate your REST API, Spring Data Rest won't even expose your entity id (it is meaningless in a REST context, what's important is how you identify the resource):
GET http://localhost:8080/person/1
{
"name":"Ron Swanson",
"age" : ...
"_links":{
"self":{
"href":"http://localhost:8080/person/1" // the resource id
}
}
}
FYI, the entity id can be provided if you tweak the configuration :
@Configuration
public class CustomRepositoryRestConfiguration extends RepositoryRestConfigurerAdapter {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration configuration) {
configuration.exposeIdsFor(Person.class);
}
}
Answered By - Marc Tarin