One-to-One Bidirectional Relationship
Learn how to make the one-to-one relationship bidirectional and resolve the JSON infinite recursion issue.
Right now, we have a unidirectional one-to-one mapping which means that if we have a Twitter account, we cannot find the name of the player who has that account. A GET request to /profiles
only gets the PlayerProfile
object and not the Player
it is associated with.
It is however possible to find the Twitter account, if we have the Player
entity. As can be seen from a GET request to /players
, the PlayerProfile
entities are also fetched.
In the unidirectional one-to-one relationship, the Player
class maintains the relationship. The PlayerProfile
class cannot see any change in the relationship.To make this relationship bidirectional, we need to make some modifications to the PlayerProfile
class. We will add a field to reference back to the Player
class and add the @OneToOne
annotation. We will also add getter and setter methods to set the Player
value in the PlayerProfile
class. This will enable us to fetch the entities in both directions.
Bi-directional relationship
To set up a bidirectional relationship, we will add a field of Player
class in the PlayerProfile
class and add getter and setter methods for the field. This field holds the reference to the associated Player
entity.
public class PlayerProfile {@Id@GeneratedValue(GenertionType.IDENTITY)private int id;private String twitter;private Player player;//...public Player getPlayer() {return player;}public void setPlayer(Player player) {this.player = player;}@Overridepublic String toString() {return "PlayerDetail [id=" + id + ", twitter=" + twitter + ", player=" + player + "]";}}
The toString()
method also needs to be updated to include the newly added player
field.
mappedBy
attribute
Next, we will add the @OneToOne
annotation on the player
field. mappedBy
is an optional attribute of the @oneToOne
annotation which specifies the name of the field which owns the relationship. In our case, it is the playerProfile
field in the Player
class. The ...