Relationships JPA Spring Boot Rest Fetch Eager

Asked

Viewed 380 times

1

I’m with an application that serves a service json Rest (not quite a Rest, but okay). The application uses Spring Boot to run, use the Pagingandsortingrepository.

The problem is that in serving an entity with many relationship to one:

@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;

He 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 wish it were so:

"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 to set it to look like this? Thanks in advance.


After deputizing my application I could notice that the State Entity is searched correctly, only it is not displayed in JSON.

1 answer

1


I managed 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 on my Repository:

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

}

I thank everyone who tried to help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.