我有以下表格:父项:
desc parent;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | varchar(255) | NO | PRI | NULL | |
+-------+--------------+------+-----+---------+-------+
孩子:
desc child;
+-----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| name | varchar(255) | NO | PRI | NULL | |
| test | varchar(255) | YES | | NULL | |
| parent_id | varchar(255) | NO | PRI | NULL | |
+-----------+--------------+------+-----+---------+-------+
在这里,在子类中,我将主键作为复合键=(name,parent_id)。
父实体:
@Entity
@AllArgsConstructor
@Table(name = "parent")
@Data
public class Parent {
@Id
@Column
private String id;
@OneToOne (mappedBy = "compKey.parent") //If I change this relationship to one-many, json ignore works fine
private Child child;
}
子类的实体:
@Entity
@Table(name = "child")
@Data
@NoArgsConstructor
public class Child {
@Embeddable
@Data
@AllArgsConstructor
public static class CompKey implements Serializable {
@OneToOne //If I change One-One to Many-One and similarly One-Many on Parent class referencing the child class, json ignore works fine
@JoinColumn
@JsonIgnore //Json ignore is not working and is giving stackoverflow exception for one to one
private Parent parent;
@Column
private String name;
}
@EmbeddedId
private CompKey compKey;
@Column
private String test;
}
现在每当我表演的时候
parentRepo.findById(id); // Thowing stackoverflow exception
我遇到了stackoverflow异常。
这种情况不会发生。如果关系在父端设置为@OneToMany,在子端设置为@ManyToOne。
如果我不使用复合键并在不使用@Embedded id的情况下将引用设置为Parent,也不会发生这种情况
范例:
@Entity
@Table(name = "child")
@Data
@NoArgsConstructor
public class Child {
@Id
@Column
private String id;
@Column
private String test;
@OneToOne
@JoinColumn
@JsonIgnore //Json ignore is working and is not giving stack overflow exception, here I am not using embedded id
private Parent parent;
}
findById在上面的情况下工作得很好,没有错误。
我想使用复合键,父表的引用包含在子表中。在使用复合键的时候,有什么原因不能设置回退引用吗?
1条答案
按热度按时间34gzjxbg1#
我不知道你想解决的问题你能在子实体中使用@MapsId吗?这里是否需要双向关系?我们可以通过共享父实体的主键来消除双向关系。让我们清理子实体类。