【问题标题】:How not to get the children of the children of the children... etc. in JPA?在JPA中如何不让孩子的孩子......等的孩子?
【发布时间】:2020-05-22 15:35:21
【问题描述】:

我可能误解了 JPA 的一些基础知识。我得到了一种关于返回对象的循环引用......

我有一个问题列表,每个问题都有一个回答列表。 但是通过我所做的 JPA 映射,每个响应也有一个问题。 看这里:

@Entity
public class Question implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // A question has several responses
    @OneToMany(mappedBy = "question", fetch = FetchType.EAGER)
    private List<Reponse> reponses;

@Entity
public class Reponse implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Long id;

    // This is here to specify the join column key "question_id"
    @ManyToOne
    @JoinColumn(name = "question_id")
    private Question question;

正如您在此处看到的,我有一个问题[0],其中包含一个响应列表,但每个问题都有一个问题,其中还有一个响应列表等等...:

如何在不带整个对象及其所有子对象等的情况下指定连接列键?

非常感谢您的帮助!

乔斯

【问题讨论】:

标签: java jpa join persistence one-to-many


【解决方案1】:

在您所做的配置中,流程按以下顺序检索数据:

  • Question对象
  • 由于FetchType.EAGER而产生的相关实体(即Response对象)
  • 再次Questionobject
  • 重复所有步骤

这是因为在“to one”关联中默认使用fetch = FetchType.EAGER

延迟加载就是答案,您必须在 question 字段上的 Response 对象中将 FetchType.LAZY 设置为 @ManyToOne(fetch = FetchType.LAZY) 以停止循环。

【讨论】:

    【解决方案2】:

    将问题更新为FetchType.LAZY

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "question_id")
    private Question question;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-16
      • 1970-01-01
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多