Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to return association objects with id in spring data rest without Projection

I am using spring-boot-starter-parent 1.4.1.RELEASE.

  1. Spring boot @ResponseBody doesn't serialize entity id by default.

If I use exposeIdsFor returns the id but I need to configure this for each class

e.g

RepositoryRestConfiguration.exposeIdsFor(User.class); RepositoryRestConfiguration.exposeIdsFor(Address.class);

Is there a simpler configuration to do this without configuring each entity class.

Refer: https://jira.spring.io/browse/DATAREST-366

  1. The REST resource will render the attribute as a URI to it’s corresponding associated resource. We need to return the associated object instead of URI.

If I use Projection, it will returns the associated objects but I need to configure this for each class

e.g

@Entity
public class Person {

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

  @ManyToOne
  private Address address;
  …
}

PersonRepository:

interface PersonRepository extends CrudRepository<Person, Long> {}

PersonRepository returns,

{
  "firstName" : "Frodo",
  "lastName" : "Baggins",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/persons/1"
    },
    "address" : {
      "href" : "http://localhost:8080/persons/1/address"
    }
  }
}

My Projection:

@Projection(name = "inlineAddress", types = { Person.class }) 
interface InlineAddress {

  String getFirstName();

  String getLastName();

  Address getAddress(); 
}

After adding projection, it returns..

{
  "firstName" : "Frodo",
  "lastName" : "Baggins",
  "address" : { 
    "street": "Bag End",
    "state": "The Shire",
    "country": "Middle Earth"
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/persons/1"
    },
    "address" : { 
      "href" : "http://localhost:8080/persons/1/address"
    }
  }
}

If some other classes having the association as an address, then I need to add projection for those classes also.

But I don't want to configure for each classes. How to implement the dynamic Projection? So that all my entities will return the nested object in response.

Refer: https://jira.spring.io/browse/DATAREST-221

like image 440
SST Avatar asked Nov 08 '22 07:11

SST


1 Answers

Regarding your first question, which was already answered here, exposeIdsFor accepts an arbitrary number of arguments. Also, as mentionned in this thread If all your entity classes are located in the same package, you could get a list of your classes using the Reflections library and feed it to exposeIdsFor().

like image 53
Marc Tarin Avatar answered Nov 14 '22 23:11

Marc Tarin