如何阻止实体在 JSON 休眠返回中重复自身?

问题描述 投票:0回答:1

我与 Aluno 和 Frequencia 之间有这种关系。一个Aluno有多个Frequencia,多个Frequencia可以对应同一个Aluno。

基于此,我创建了以下关系:

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<>();
}

班级频率

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;

    
}

必须添加注释

@JsonBackReference
@JsonManagedReference
,因为“Aluno有一个频率列表,每个频率都有一个Aluno,它有一个频率列表”的循环......等等导致了StackOverflowException

但现在它导致了“另一个”问题(我猜是由递归引起的)。当我的 JSON 返回时,在 Aluno 的 Frequencia 属性上,它会再次重复 Aluno 数据,而我只需要 Frequencia 数据(idFrequencia、presenca 和 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"
                }
            ]
        }

尝试想一种方法来消除递归,例如将Frequencias中的Aluno更改为Integer而不是EntityClass,但这也会导致错误。

java hibernate rest jpa spring-data-jpa
1个回答
0
投票

这是预期的,因为您已经定义了双向关系,您在 Frequencia 实体中定义了 Aluno,因此您得到了后者的结果。我建议您尽可能多地使用DTO类,返回实体不是最好的方法。如果不需要获取与频率相关的 aluno,则可以删除 @ManyToOne 映射。

© www.soinside.com 2019 - 2024. All rights reserved.