Search code examples
javahibernaterestjpaspring-data-jpa

How can I stop the entity repeating itself in my JSON hibernate return?


I have this relationship between Aluno and Frequencia. One Aluno has multiple Frequencia's, and multiple Frequencia's can correspond to the same Aluno.

Based on this, I created the following relationship:

Class Aluno:

public class Aluno {

    @Id
    private Integer idAluno;
    private boolean status;

    /* rest of the attributes */

    @OneToMany(fetch = FetchType.LAZY,mappedBy = "aluno")
    @JsonBackReference
    private List<Frequencia> frequencias = new ArrayList<>();
}

Class Frequencia

public class Frequencia {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id_frequencia", nullable = false)
    private Integer idFrequencia;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "aluno_id_aluno")
    private Aluno aluno;

    private boolean presenca;
    private Date data;

    
}

Had to put the annotations @JsonBackReference and @JsonManagedReference because the loop of "Aluno has a List of Frequencia, and each frequencia has a Aluno, which has a list of Frequencia" ... an so on was causing a StackOverflowException

But now it's causing "another" problem (caused by the recursion I guess). When my JSON is returned, on the Frequencia attribute of the Aluno, it repeats the Aluno data all over again, and I need just the Frequencia data (idFrequencia,presenca and data)

{
            "idAluno": 102227,
            "nome": "John F. Kennedy,
            "status": true,
                         /* rest of the attributes */
            "frequencias": [
                {
                    "idFrequencia": 2,
                    "aluno": {
                        "idAluno": 102227,
                                    "nome": "John F. Kennedy,
                                    "status": true,
                                                /* rest of the attributes */
                    },
                    "presenca": true,
                    "data": "2024-10-01T03:00:00.000+00:00"
                }
            ]
        }

Tried thinking of a way to remove the recursion like changing the Aluno in Frequencias to a Integer instead of EntityClass, but it results in errors too.


Solution

  • This is expected as you have defined a bidirectional relationship, You have Aluno defined in your Frequencia entity and thus you get the latter with your result. I suggest you to use DTO classes as much as much as possible, returning an entity is not the best way. If there is not a case where you have to get the aluno related to the frequencia you can remove the @ManyToOne mapping.