Search code examples
angularjsangularjs-scopejsonserializer

avoid Infinite recursion relationships with serializer (angularjs)


I am currently trying to implement a RESTful application with @OneToMany relationships.

My entities are Team and Player (one Team, many Players - one Player to exactly one Team)

To avoid the infinite recursion I decided to use a serializer that returns the id. This serializer was added as an annotation to the match attribute.

It works fine when I check it with postman. But when I try to show the values in my frontend the teamid of the players is shown in the JSON format (see picture).

picture of my problem

How can I change the id value to a simple number? Is this an angular problem? I am new to this framework and just copied a simple controller to view the results in a ng-repeat looped table

Here are my entities:

Team:

@Entity
@Table(name = "TEAMS")
public class Team {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;

@Column(name = "TEAMNAME")
private String teamname;

@OneToMany(mappedBy = "team")
private List<Player> players;

//..getter/setter etc..
}

Player:

@Entity
@Table(name = "PLAYERS")
public class Player {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;

@Column(name = "NAME")
private String name;

@ManyToOne
@JoinColumn(name = "TEAMID")
@JsonSerialize(using = TeamSerializer.class)
private Team team;

//..getter/setter etc.

The serializer:

public class TeamSerializer extends JsonSerializer<Team>{

@Override
public void serialize(Team team, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeNumberField("id", team.getId());
    jgen.writeEndObject();

  }
}

and the app.js entry:

app.controller({
PlayerListController: function($scope, Player) {
    $scope.players = Player.query();
}
});

and call it via:

<tr ng-repeat="player in players">
    <td>{{player.id}}</td>
    <td>{{player.name}}</td>
    <td>{{player.team}}</td>
</tr>

Solution

  • How can I change the id value to a simple number?

    Change from:

    <td>{{player.team}}</td>
    

    to:

    <td>{{player.team.id}}</td>