java – Circular dependency on API Rest with Spring Boot

Question:

I'm venturing into developing a Rest API using Spring Boot, JPA with Hibernate and Maven to manage the repositories. In my modeling I have a Club class:

@Entity
@Table( name = "CLUB")
public class Club {

   /**
    * Id da entidade
    */
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;

    /**
    * Atual técnico do clube.
    */
   @OneToOne(mappedBy = "actualClub")
   private Coach coach;
   
   //Outros atributos, getters e setters
  }

which has an @OneToOne relationship with the Coach class:

@Entity
@Table(name = "COACH")
public class Coach extends Person {

   /**
    * Clube atual do técnico.
    */
   @OneToOne
   @JoinColumn(name = "CLUB_ID")
   private Club actualClub;

   //Outros atributos, getters e setters
   
}

The Person class has some additional attributes, among them the id , which follows the same logic implemented in Club .

Finally, I also have the ClubController class to handle some requests:

 @RestController public class ClubController { /** * Instância da classe de serviços da entidade <i>Club</i> */ @Autowired private ClubService clubService; /** * Retorna JSON que representa o clube com o 'id' especificado. * * @param id Identificador do clube a ser buscado. * @return ResponseEntity Objeto com detalhes da requisição HTTP, como o Status. */ @RequestMapping(value = "/clubs/{id}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET) public ResponseEntity<?> getClubById(@PathVariable Long id) { final Club club = this.clubService.findById(id); if (club != null) { return new ResponseEntity<>(club, HttpStatus.FOUND); } else { return new ResponseEntity<>("Não encontrado", HttpStatus.NOT_FOUND); } } /*Entre outros métodos...*/ }

The problem I'm having is that the returned JSON has a circular relationship between Club and Coach . That is, I receive the club's data, including the coach's data. Within the coach's attributes there is again the club's data and so on… x(

And that will certainly happen when I relate Club to Player later on.

One solution I found was this: Link . Which uses @JsonIdentityInfo in class declarations. One problem I noticed with this solution is the overhead of information that isn't always needed. For example, when I go @OneToMany with Player , I would necessarily bring all the player information when searching for a club.

Searching a little further, I found another possible solution (not tested yet) from Sring itself: Spring HATEOAS . That way I would be able to add links (href) for certain attributes, and only make the request for more information if really necessary. But I also saw that HATEOAS still has some limitations.

So my question is: what would be the best approach for these cases? Do you have any other options?

My further idea is to consume this API in an iOS app. (This may be important to help with the answer)

Answer:

I treat this reference as follows.

On the side of the association that I want the json to be generated I @JsonManagedReference the attribute with @JsonManagedReference , and on the other side I @JsonBackReference with @JsonBackReference .

If in the object serialization the @JsonBackReference is found, in this object this attribute will not be serialized because the other side carries this responsibility,

Scroll to Top
AllEscort