Custom response for root request int the Spring REST HATEOAS with both RepositoryRestResource-s and regular controllers - spring

Let's say I have two repositories:
#RepositoryRestResource(collectionResourceRel = "person", path = "person")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
List<Person> findByLastName(#Param("name") String name);
}
and
#RepositoryRestResource(collectionResourceRel = "person1", path = "person1")
public interface PersonRepository1 extends PagingAndSortingRepository<Person1, Long> {
List<Person1> findByLastName(#Param("name") String name);
}
with one regular controller:
#Controller
public class HelloController {
#RequestMapping("/hello")
#ResponseBody
public HttpEntity<Hello> hello(#RequestParam(value = "name", required = false, defaultValue = "World") String name) {
Hello hello = new Hello(String.format("Hello, %s!", name));
hello.add(linkTo(methodOn(HelloController.class).hello(name)).withSelfRel());
return new ResponseEntity<>(hello, HttpStatus.OK);
}
}
Now, a response for http://localhost:8080/ is:
{
"_links" : {
"person" : {
"href" : "http://localhost:8080/person{?page,size,sort}",
"templated" : true
},
"person1" : {
"href" : "http://localhost:8080/person1{?page,size,sort}",
"templated" : true
}
}
}
but I want to get something like this:
{
"_links" : {
"person" : {
"href" : "http://localhost:8080/person{?page,size,sort}",
"templated" : true
},
"person1" : {
"href" : "http://localhost:8080/person1{?page,size,sort}",
"templated" : true
},
"hello" : {
"href" : "http://localhost:8080/hello?name=World"
}
}
}

#Component
public class HelloResourceProcessor implements ResourceProcessor<RepositoryLinksResource> {
#Override
public RepositoryLinksResource process(RepositoryLinksResource resource) {
resource.add(ControllerLinkBuilder.linkTo(HelloController.class).withRel("hello"));
return resource;
}
}
based on
http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.customizing-json-output
How to add links to root resource in Spring Data REST?

You need to have a ResourceProcessory for your Person resource registered as a Bean. see https://stackoverflow.com/a/24660635/442773

Related

Remove association links for content on collection resource for Spring Data REST

How configure Spring Data REST to remove entity association links (left only "self") on Collection resource response of Repository interface endpoints, without set exported=false on #ResResource annotation (need keep exported the endpoints)
We has entities where the _links part has the bigest size on the response:
On Item resource _ links are useful to navigate throught the associations.
But on Collection Resources , mainly on large collections, this information is not important and makes the response unnecesary biger .
We need change this response:
{
"_embedded" : {
"persons" : [ {
"id" : "bat_3191",
"name" : "B",
"_links" : { // 80% of response size !!
"self" : {
"href" : "http://localhost:8080/api/persons/bat_3191"
},
"orders" : {
"href" : "http://localhost:8080/api/persons/bat_3191/order"
},
"payments" : {
"href" : "http://localhost:8080/api/persons/bat_3191/payments"
},
"childrens" : {
"href" : "http://localhost:8080/api/persons/bat_3191/childrens"
},
"invoices" : {
"href" : "http://localhost:8080/api/persons/bat_3191/invoices"
},
"brands" : {
"href" : "http://localhost:8080/api/persons/bat_3191/brands"
},
}
},
{ person [2] }
...
{ person [N] }
]
},
"_links" : {
[page links]
}
To a only "self" on _links part:
{
"_embedded" : {
"persons" : [ {
"id" : "bat_3191",
"name" : "B",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/persons/bat_3191"
}
}
}, {
"id" : "bat_2340",
"name" : "B",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/persons/bat_2340"
}
}
If I wanted to control the hateos links in springboot I used a resource assembler. As an example:
#Autowired
private EmployeeAddressResourceAssembler assembler;
#GetMapping(value="/{empId}", produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<EmployeeAddressResource> getEmployeeAddress(#PathVariable Integer empId) {
EmployeeAddressItem employeeAddressItem = restTemplate.getForObject(
serviceUrl + "/employee/address/{empId}",
EmployeeAddressItem.class, empId);
return ResponseEntity.ok( assembler.toResource(employeeAddressItem) );
}
And then I used the resource assembler.
#Component
public class EmployeeAddressResourceAssembler
extends ResourceAssemblerSupport<EmployeeAddressItem, EmployeeAddressResource> {
public EmployeeAddressResourceAssembler() {
super(EmployeeAddressController.class, EmployeeAddressResource.class);
}
#Override
public EmployeeAddressResource toResource(EmployeeAddressItem item) {
// createResource(employeeAddressItem);
EmployeeAddressResource resource = createResourceWithId(item.getEmpId(), item);
resource.fromEmployeeAddressItem(item);
// … do further mapping
resource.add(linkTo(methodOn(EmployeeAddressController.class).deleteEmployeeAddress(item.getEmpId())).withRel("delete"));
return resource;
}
}
and the ResourceAssembler uses a Resource
public class EmployeeAddressResource extends ResourceSupport {
private Integer empId;
private String address1;
private String address2;
private String address3;
private String address4;
private String state;
private String country;
public void fromEmployeeAddressItem(EmployeeAddressItem item) {
this.empId = item.getEmpId();
this.address1 = item.getAddress1();
this.address2 = item.getAddress2();
this.address3 = item.getAddress3();
this.address4 = item.getAddress4();
this.state = item.getState();
this.country = item.getCountry();
}
All this at RestPracticeWithHateos

Preserving hostname on HATEOAS Resource with OpenFeign

I'm trying to add a URI to a resource located in a different microservice using OpenFeign and a ResourceAssembler, while preserving the hostname from the original request.
When making a REST request to a HATEOAS resource in another microservice, the resource.getId() method returns a link where the hostname is the Docker container hash instead of the original hostname used to make the request.
Controller
#RestController
#RequestMapping("/bulletins")
public class BulletinController {
// Autowired dependencies
#GetMapping(produces = MediaTypes.HAL_JSON_VALUE)
public ResponseEntity<PagedResources<BulletinResource>> getBulletins(Pageable pageable) {
Page<Bulletin> bulletins = bulletinRepository.findAll(pageable);
return ResponseEntity.ok(pagedResourceAssembler.toResource(bulletins, bulletinResourceAssembler));
}
}
Assembler
#Component
public class BulletinResourceAssembler extends ResourceAssemblerSupport<Bulletin, BulletinResource> {
private final AdministrationService administrationService;
#Autowired
public BulletinResourceAssembler(AdministrationService administrationService) {
super(BulletinController.class, BulletinResource.class);
this.administrationService = administrationService;
}
#Override
public BulletinResource toResource(Bulletin entity) {
Resource<Site> siteRessource = administrationService.getSiteBySiteCode(entity.getSiteCode());
\\ Set other fields ...
bulletinRessource.add(siteRessource.getId().withRel("site"));
return bulletinRessource;
}
}
Feign Client
#FeignClient(name = "${feign.administration.serviceId}", path = "/api")
public interface AdministrationService {
#GetMapping(value = "/sites/{siteCode}")
Resource<Site> getSiteBySiteCode(#PathVariable("siteCode") String siteCode);
}
Bulletin Resource
#Data
public class BulletinResource extends ResourceSupport {
// fields
}
Expected result
curl http://myhost/api/bulletins
{
"_embedded" : {
"bulletinResources" : [ {
"entityId" : 1,
"_links" : {
"self" : {
"href" : "http://myhost/api/bulletins/1"
},
"site" : {
"href" : "http://myhost/api/sites/000"
}
}
} ]
},
[...]
}
Actual result
curl http://myhost/api/bulletins
{
"_embedded" : {
"bulletinResources" : [ {
"entityId" : 1,
"_links" : {
"self" : {
"href" : "http://myhost/api/bulletins/1"
},
"site" : {
"href" : "http://b4dc1a02586c:8080/api/sites/000"
}
}
} ]
},
[...]
}
Notice the site href is b4dc1a02586c, which is the Docker container id.
The solution was to manually define a RequestInterceptor for the FeignClient and manually add the X-Forwarded-Host header, as well as define a ForwardedHeaderFilter bean in the service the request was made to.
Client Side
public class ForwardHostRequestInterceptor implements RequestInterceptor {
private static final String HOST_HEADER = "Host";
private static final String X_FORWARDED_HOST = "X-Forwarded-Host";
#Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
if (requestAttributes == null) {
return;
}
HttpServletRequest request = requestAttributes.getRequest();
String host = request.getHeader(X_FORWARDED_HOST);
if (host == null) {
host = request.getHeader(HOST_HEADER);
}
requestTemplate.header(X_FORWARDED_HOST, host);
}
}
Producer side
The producer side also required modification as per the discussion on
https://github.com/spring-projects/spring-hateoas/issues/862
which refers to the following documentation
https://docs.spring.io/spring-hateoas/docs/current-SNAPSHOT/reference/html/#server.link-builder.forwarded-headers
which states to add the following bean in order to use forward headers.
#Bean
ForwardedHeaderFilter forwardedHeaderFilter() {
return new ForwardedHeaderFilter();
}

Spring Boot HATEOAS Output Fails

The output of my entities in a Sprint Boot REST HATEOAS service does not work. The service returns an empty string for each entity. There are no error messages. I have tried Spring Boot 1.5.4 and 2.0.0.RC1.
Full source code is on GitHub: https://github.com/murygin/hateoas-people-service
Application
#SpringBootApplication
#Configuration
#EnableHypermediaSupport(type={EnableHypermediaSupport.HypermediaType.HAL})
public class Application {
public static void main(String args[]) {
SpringApplication.run(Application.class);
}
}
PersonController
#RestController
#RequestMapping(value = "/persons", produces = "application/hal+json")
public class PersonController {
#GetMapping
public ResponseEntity<Resources<PersonResource>> all() {
final List<PersonResource> collection =
getPersonList().stream().map(PersonResource::new).collect(Collectors.toList());
final Resources<PersonResource> resources = new Resources<>(collection);
final String uriString = ServletUriComponentsBuilder.fromCurrentRequest().build().toUriString();
resources.add(new Link(uriString, "self"));
return ResponseEntity.ok(resources);
}
#GetMapping("/{id}")
public ResponseEntity<PersonResource> get(#PathVariable final long id) {
Person p = new Person((long)1,"Donald","Duck");
return ResponseEntity.ok(new PersonResource(p));
}
private List<Person> getPersonList() {
List<Person> personList = new LinkedList<>();
personList.add(new Person((long)1,"Donald","Duck"));
personList.add(new Person((long)2,"Dagobert","Duck"));
personList.add(new Person((long)3,"Daniel","Duesentrieb"));
return personList;
}
}
PersonResource
public class PersonResource extends ResourceSupport {
private final Person person;
public PersonResource(final Person person) {
this.person = person;
final long id = person.getId();
add(linkTo(PersonController.class).withRel("people"));
add(linkTo(methodOn(PersonController.class).get(id)).withSelfRel());
}
}
Person
public class Person {
private Long id;
private String firstName;
private String secondName;
public Person() {
}
public Person(Long id, String firstName, String secondName) {
this.id = id;
this.firstName = firstName;
this.secondName = secondName;
}
// getter and setter...
}
Output of http://localhost:8080/persons
{
_embedded: {
personResourceList: [{
_links: {
people: {
href: "http://localhost:8080/persons"
},
self: {
href: "http://localhost:8080/persons/1"
}
}
},
{
_links: {
people: {
href: "http://localhost:8080/persons"
},
self: {
href: "http://localhost:8080/persons/2"
}
}
},
{
_links: {
people: {
href: "http://localhost:8080/persons"
},
self: {
href: "http://localhost:8080/persons/3"
}
}
}
]
},
_links: {
self: {
href: "http://localhost:8080/persons"
}
}
}
Output of http://localhost:8080/persons/1
{
_links: {
people: {
href: "http://localhost:8080/persons"
},
self: {
href: "http://localhost:8080/persons/1"
}
}
}
Add a getter for person in PersonResource:
public class PersonResource extends ResourceSupport {
private final Person person;
public PersonResource(final Person person) {
this.person = person;
final long id = person.getId();
add(linkTo(PersonController.class).withRel("people"));
add(linkTo(methodOn(PersonController.class).get(id)).withSelfRel());
}
public Person getPerson() {
return person;
}
}
With the getter, Spring gets the person wrapped in your PersonResource and serializes it:
GET http://localhost:8080/persons/1
{
"person" : {
"id" : 1,
"firstName" : "Donald",
"secondName" : "Duck"
},
"_links" : {
"people" : {
"href" : "http://localhost:8080/persons"
},
"self" : {
"href" : "http://localhost:8080/persons/1"
}
}
}
GET http://localhost:8080/persons
{
"_embedded" : {
"personResources" : [ {
"person" : {
"id" : 1,
"firstName" : "Donald",
"secondName" : "Duck"
},
"_links" : {
"people" : {
"href" : "http://localhost:8080/persons"
},
"self" : {
"href" : "http://localhost:8080/persons/1"
}
}
}, {
"person" : {
"id" : 2,
"firstName" : "Dagobert",
"secondName" : "Duck"
},
"_links" : {
"people" : {
"href" : "http://localhost:8080/persons"
},
"self" : {
"href" : "http://localhost:8080/persons/2"
}
}
}, {
"person" : {
"id" : 3,
"firstName" : "Daniel",
"secondName" : "Duesentrieb"
},
"_links" : {
"people" : {
"href" : "http://localhost:8080/persons"
},
"self" : {
"href" : "http://localhost:8080/persons/3"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/persons"
}
}
}
Note: I'm a lazy bum, I added spring-boot-starter-data-rest to the pom.xml dependencies to pretty print the result, so your actual result may vary a bit.
I suggest you a pretty less invasive approach for your case with the use of Resource instead of the extending of ResourceSupport. Your code would look like this:
#RestController
#RequestMapping(value = "/persons", produces = "application/hal+json")
public class PersonController {
#GetMapping
public ResponseEntity<List<Resource<Person>>> all() {
final List<Resource<Person>> collection =
getPersonList().stream()
.map(p -> new Resource<>(p, this.getLinks(p.getId())))
.collect(Collectors.toList());
return ResponseEntity.ok(collection);
}
#GetMapping("/{id}")
public ResponseEntity<Resource<Person>> get(#PathVariable final long id) {
Person p = new Person(id,"Donald","Duck");
Resource<Person> resource = new Resource<>(p, this.getLinks(id));
return ResponseEntity.ok(resource);
}
private List<Person> getPersonList() {
List<Person> personList = new LinkedList<>();
personList.add(new Person((long)1,"Donald","Duck"));
personList.add(new Person((long)2,"Dagobert","Duck"));
personList.add(new Person((long)3,"Daniel","Duesentrieb"));
return personList;
}
private List<Link> getLinks(long id) {
return Arrays.asList(
linkTo(PersonController.class).withRel("people"),
linkTo(methodOn(getClass()).get(id)).withSelfRel());
}
}
With more clear outputs:
GET http://localhost:8080/persons/1
{
"id": 1,
"firstName": "Donald",
"secondName": "Duck",
"_links": {
"people": {"href": "http://localhost:8080/persons"},
"self": {"href": "http://localhost:8080/persons/1"}
}
}
GET http://localhost:8080/persons
[
{
"id": 1,
"firstName": "Donald",
"secondName": "Duck",
"_links": {
"people": {"href": "http://localhost:8080/persons"},
"self": {"href": "http://localhost:8080/persons/1"}
}
},
{
"id": 2,
"firstName": "Dagobert",
"secondName": "Duck",
"_links": {
"people": {"href": "http://localhost:8080/persons"},
"self": {"href": "http://localhost:8080/persons/2"}
}
},
{
"id": 3,
"firstName": "Daniel",
"secondName": "Duesentrieb",
"_links": {
"people": {"href": "http://localhost:8080/persons"},
"self": {"href": "http://localhost:8080/persons/3"}
}
}
]
Just another point of view, hope this helps.

Displaying Data with Spring JPA and REST

Following these tutorials 1, 2, I successfully made a RESTful Spring application combined with JPA. Currently, I have 3 drivers in my Driver repository.
My problem is when I go on localhost:8080/driver, it says this:
{
"_embedded" : {
"driver" : [ {
"_links" : {
"self" : {
"href" : "http://localhost:8080/driver/1"
},
"driver" : {
"href" : "http://localhost:8080/driver/1"
}
}
}, {
"_links" : {
"self" : {
"href" : "http://localhost:8080/driver/2"
},
"driver" : {
"href" : "http://localhost:8080/driver/2"
}
}
}, {
"_links" : {
"self" : {
"href" : "http://localhost:8080/driver/3"
},
"driver" : {
"href" : "http://localhost:8080/driver/3"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/driver"
},
"profile" : {
"href" : "http://localhost:8080/profile/driver"
},
"search" : {
"href" : "http://localhost:8080/driver/search"
}
},
"page" : {
"size" : 20,
"totalElements" : 3,
"totalPages" : 1,
"number" : 0
}
}
and when I go onto a particular's drivers page, something like localhost:8080/driver/1, it says this:
{
"_links" : {
"self" : {
"href" : "http://localhost:8080/driver/1"
},
"driver" : {
"href" : "http://localhost:8080/driver/1"
}
}
}
In my Driver Entity Class, I have fields like firstName, lastName, telephone and stuff like that. My question is: is there a way I can display on it either localhost:8080/driver or localhost:8080/driver/1? So that it looks similar to this:
{
"firstName" : "Frodo",
"lastName" : "Baggins",
"_links" : {
"self" : {
"href" : "http://localhost:8080/people/1"
}
}
}
I know the fields are properly saved in the database, because I can successfully search for them, but I haven't yet found an example of how to display them, except POSTing with curl.
Thanks in advance to anyone who can help!
Edit: This is my Starter class:
#SpringBootApplication
public class StartServer implements ApplicationListener<ContextRefreshedEvent> {
private static final Logger log = LoggerFactory.getLogger(StartServer.class);
public static void main(String[] args) {
SpringApplication.run(StartServer.class, args);
}
#Override
public void onApplicationEvent(final ContextRefreshedEvent event) {
}
#Bean
public CommandLineRunner demo(DriverRepository repository) {
return (args) -> {
repository.save(new Driver("Jack", "Bauer"));
repository.save(new Driver("JackY", "Aasd"));
repository.save(new Driver("JackMe", "Commou"));
// fetch all customers
log.info("Drivers found with findAll():");
log.info("-------------------------------");
for (Driver driver : repository.findAll()) {
log.info(driver.toString());
}
log.info("");
Driver driver = repository.findOne(1L);
log.info("Customer found with findOne(1L):");
log.info("--------------------------------");
log.info(driver.toString());
log.info("");
// fetch customers by last name
log.info("Driver found with findByLastName('Bauer'):");
log.info("--------------------------------------------");
for (Driver bauer : repository.findByLastName("Bauer")) {
log.info(bauer.toString());
}
log.info("");
};
}
}
And my DriverRepository class:
#RepositoryRestResource(collectionResourceRel = "driver", path = "driver")
public interface DriverRepository extends PagingAndSortingRepository<Driver, Long> {
List<Driver> findByLastName(#Param("name") String name);
}
I do not have a Controller Class for /driver, because the #RepositoryRestResource(collectionResourceRel = "driver", path = "driver") took care of it for me.
My Driver Entity class:
#Entity
public class Driver {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
String firstName;
String lastName;
protected Driver() {
}
public Driver(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return String.format( "Customer[id=%d, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}

Getting duplicate items when querying a collection with Spring Data Rest

I'm having duplicate results on a collection with this simple model: an entity Module and an entity Page. A Module has a set of pages, and a Page belongs to the module.
This is set up with Spring Boot with Spring Data JPA and Spring Data Rest.
The full code is accessible on GitHub
Entities
Here's the code for the entities. Most setters removed for brevity:
Module.java
#Entity
#Table(name = "dt_module")
public class Module {
private Long id;
private String label;
private String displayName;
private Set<Page> pages;
#Id
public Long getId() {
return id;
}
public String getLabel() {
return label;
}
public String getDisplayName() {
return displayName;
}
#OneToMany(mappedBy = "module")
public Set<Page> getPages() {
return pages;
}
public void addPage(Page page) {
if (pages == null) {
pages = new HashSet<>();
}
pages.add(page);
if (page.getModule() != this) {
page.setModule(this);
}
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Module module = (Module) o;
return Objects.equals(label, module.label) && Objects.equals(displayName, module.displayName);
}
#Override
public int hashCode() {
return Objects.hash(label, displayName);
}
}
Page.java
#Entity
#Table(name = "dt_page")
public class Page {
private Long id;
private String name;
private String action;
private String description;
private Module module;
#Id
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getAction() {
return action;
}
public String getDescription() {
return description;
}
#ManyToOne
public Module getModule() {
return module;
}
public void setModule(Module module) {
this.module = module;
this.module.addPage(this);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Page page = (Page) o;
return Objects.equals(name, page.name) &&
Objects.equals(action, page.action) &&
Objects.equals(description, page.description) &&
Objects.equals(module, page.module);
}
#Override
public int hashCode() {
return Objects.hash(name, action, description, module);
}
}
Repositories
Now the code for the Spring repositories, which is fairly simple:
ModuleRepository.java
#RepositoryRestResource(collectionResourceRel = "module", path = "module")
public interface ModuleRepository extends PagingAndSortingRepository<Module, Long> {
}
PageRepository.java
#RepositoryRestResource(collectionResourceRel = "page", path = "page")
public interface PageRepository extends PagingAndSortingRepository<Page, Long> {
}
Config
The configuration comes from 2 files:
Application.java
#EnableJpaRepositories
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
application.properties
spring.jpa.database = H2
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.generate-ddl=false
spring.jpa.hibernate.ddl-auto=validate
spring.datasource.initialize=true
spring.datasource.url=jdbc:h2:mem:demo;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.data.rest.basePath=/api
Database
Finally the db schema and some test data:
schema.sql
drop table if exists dt_page;
drop table if exists dt_module;
create table DT_MODULE (
id IDENTITY primary key,
label varchar(30) not NULL,
display_name varchar(40) not NULL
);
create table DT_PAGE (
id IDENTITY primary key,
name varchar(50) not null,
action varchar(50) not null,
description varchar(255),
module_id bigint not null REFERENCES dt_module(id)
);
data.sql
INSERT INTO DT_MODULE (label, display_name) VALUES ('mod1', 'Module 1'), ('mod2', 'Module 2'), ('mod3', 'Module 3');
INSERT INTO DT_PAGE (name, action, description, module_id) VALUES ('page1', 'action1', 'desc1', 1);
That's about it. Now, I run thus from the command line to start the application: mvn spring-boot:run. After the application starts, I can query it's main endpoint like this:
Get API
$ curl http://localhost:8080/api
Response
{
"_links" : {
"page" : {
"href" : "http://localhost:8080/api/page{?page,size,sort}",
"templated" : true
},
"module" : {
"href" : "http://localhost:8080/api/module{?page,size,sort}",
"templated" : true
},
"profile" : {
"href" : "http://localhost:8080/api/alps"
}
}
}
Get all modules
curl http://localhost:8080/api/module
Response
{
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/module"
}
},
"_embedded" : {
"module" : [ {
"label" : "mod1",
"displayName" : "Module 1",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/module/1"
},
"pages" : {
"href" : "http://localhost:8080/api/module/1/pages"
}
}
}, {
"label" : "mod2",
"displayName" : "Module 2",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/module/2"
},
"pages" : {
"href" : "http://localhost:8080/api/module/2/pages"
}
}
}, {
"label" : "mod3",
"displayName" : "Module 3",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/module/3"
},
"pages" : {
"href" : "http://localhost:8080/api/module/3/pages"
}
}
} ]
},
"page" : {
"size" : 20,
"totalElements" : 3,
"totalPages" : 1,
"number" : 0
}
}
Get all pages for one module
curl http://localhost:8080/api/module/1/pages
Response
{
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/module/1/pages"
}
},
"_embedded" : {
"page" : [ {
"name" : "page1",
"action" : "action1",
"description" : "desc1",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/page/1"
},
"module" : {
"href" : "http://localhost:8080/api/page/1/module"
}
}
}, {
"name" : "page1",
"action" : "action1",
"description" : "desc1",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/page/1"
},
"module" : {
"href" : "http://localhost:8080/api/page/1/module"
}
}
} ]
}
}
So as you can see, I'm getting the same page twice here. What's going on?
Bonus question: Why this works?
I was cleaning the code to submit this question, and in order to make it more compact, I moved the JPA Annotations on the Page entity to field level, like this:
Page.java
#Entity
#Table(name = "dt_page")
public class Page {
#Id
private Long id;
private String name;
private String action;
private String description;
#ManyToOne
private Module module;
...
All the rest of the class remains the same. This can be seen on the same github repo on branch field-level.
As it turns out, executing the same request with that change to the API will render the expected result (after starting the server the same way I did before):
Get all pages for one module
curl http://localhost:8080/api/module/1/pages
Response
{
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/module/1/pages"
}
},
"_embedded" : {
"page" : [ {
"name" : "page1",
"action" : "action1",
"description" : "desc1",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/page/1"
},
"module" : {
"href" : "http://localhost:8080/api/page/1/module"
}
}
} ]
}
}
This is causing your issue (Page Entity):
public void setModule(Module module) {
this.module = module;
this.module.addPage(this); //this line right here
}
Hibernate uses your setters to initialize the entity because you put the JPA annotations on getters.
Initialization sequence that causes the issue:
Module object created
Set Module properties (pages set is initialized)
Page object created
Add the created Page to Module.pages
Set Page properties
setModule is called on the Page object and this adds (addPage) the current Page to Module.pages the second time
You can put the JPA annotations on the fields and it will work, because setters won't be called during initialization (bonus question).
I had this issue and I just changed fetch=FetchType.EAGER to fetch=FetchType.LAZY
This solved my problem!

Resources