I am venturing into developing a Rest API using Spring Boot, JPA with Hibernate and Maven to manage repositories.
In my modeling I have a class Club
:
@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 a @OneToOne
relationship with class Coach
:
@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 class Person
has some additional attributes, including id
, which follows the same logic implemented in Club
.
Finally, I also have the class ClubController
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 get the club's data, including the coach's data. Within the attributes of the coach there is again the data of the club and so continues ... x
And this is certainly going to happen also when I relate Club
to Player
later.
One solution I found was this: Link . That uses @JsonIdentityInfo
in class declaration. One problem I noticed in this solution is the overhead of information that is not always needed. For example, when I am @OneToMany
with Player
, I would necessarily fetch all player information when searching for a club.
Further research, I found another possible solution (not yet tested) by Sring himself: Spring HATEOAS . That way I would be able to add links (href) to certain attributes, and would only make the request for more information if it really needed it. But I also saw that HATEOAS still has some limitations.
So my question is: what would be the best approach for such cases? Do you have any other options?
My idea is to consume this API in an iOS application. (This may be important to help with the answer.)