Relationships JPA Spring Boot Rest Fetch Eager

1

I have an application that serves a rest service json (not quite a rest, but okay). The application uses Spring Boot to run, I use the PagingAndSortingRepository.

The problem is that when serving an entity with Many to One relationship:

@Entity
public class City {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(targetEntity=State.class, fetch = FetchType.EAGER)
    @JoinColumn(name="state_id")
    private State state;

It delivers like this:

"id" : 1,
"name" : "Cidade exemplo",
"capital" : true,
"_links" : {
    "self" : {
        "href" : "http://meu_dominio/rest/cities/1"
    },
    "city" : {
      "href" : "http://meu_dominio/rest/cities/1"
    },
    "state" : {
      "href" : "http://meu_dominio/rest/cities/1/state"
    }
}

But I wanted it to be like this:

"id" : 1,
"name" : "Cidade exemplo",
"capital" : true,
"state" : {
    "id" : 1,
    "name" : "Estado Exemplo",
    "initials" : "EX",
    "_links" : {
        "self" : {
            "href" : "http://meu_dominio/rest/states/1"
         },
        "state" : {
            "href" : "http://meu_dominio/rest/states/1"
        }
    }
},
"_links" : {
    "self" : {
      "href" : "http://meu_dominio/rest/cities/1"
    },
    "city" : {
      "href" : "http://meu_dominio/rest/cities/1"
    }
}

How do I configure it to look like this? Thank you in advance.

After deferring my application, I realized that the State Entity is searched correctly, it just does not appear in JSON.

    
asked by anonymous 19.05.2016 / 20:41

1 answer

1

I was able to solve using Projections. So:

import org.springframework.data.rest.core.config.Projection;

@Projection(name = "fullCity", types = { City.class })
public interface CityProjection {

    Long getId();
    String getName();
    boolean getCapital();
    State getState();

}

And in my Repository:

@RepositoryRestResource(excerptProjection = CityProjection.class)
public interface Cities extends PagingAndSortingRepository<City, Long>{

}

Thanks to everyone who tried to help.

    
27.05.2016 / 18:31