如何在 JPA 中不获取 children 的 children 的 children... 等等?
How not to get the children of the children of the children... etc. in JPA?
我可能误解了 JPA 的一些基础知识。我在返回的 objects 上得到了一种循环引用...
我有一个问题列表,每个问题都有一个答案列表。
但是对于我所做的 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],其中有一个回复列表,但每个问题都有一个问题,其中也有一个回复列表等等...:[=15=]
如何指定连接列键而不必带上整个 object 和他的所有 children 等等?
非常感谢您的帮助!
乔斯
将问题更新为FetchType.LAZY
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "question_id")
private Question question;
在您执行的配置中,流程按以下顺序检索数据:
Question
对象
- 相关实体(即
Response
个对象)由于 FetchType.EAGER
Question
再次对象
- 重复所有步骤
这是因为在 "to one" 关联中默认使用 fetch = FetchType.EAGER
。
延迟加载就是答案,您必须在 question
字段上的 Response
对象中将 FetchType.LAZY
设置为 @ManyToOne(fetch = FetchType.LAZY)
以停止循环。
我可能误解了 JPA 的一些基础知识。我在返回的 objects 上得到了一种循环引用...
我有一个问题列表,每个问题都有一个答案列表。 但是对于我所做的 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],其中有一个回复列表,但每个问题都有一个问题,其中也有一个回复列表等等...:[=15=]
如何指定连接列键而不必带上整个 object 和他的所有 children 等等?
非常感谢您的帮助!
乔斯
将问题更新为FetchType.LAZY
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "question_id")
private Question question;
在您执行的配置中,流程按以下顺序检索数据:
Question
对象- 相关实体(即
Response
个对象)由于FetchType.EAGER
Question
再次对象- 重复所有步骤
这是因为在 "to one" 关联中默认使用 fetch = FetchType.EAGER
。
延迟加载就是答案,您必须在 question
字段上的 Response
对象中将 FetchType.LAZY
设置为 @ManyToOne(fetch = FetchType.LAZY)
以停止循环。