java-@OneToMany映射JPA中的父ID为null

我在父子关系中使用javax.persistence.OneToMany关系.父ID为null,我已经阅读了Stackoverflow中的所有相关文章,但没有得到我所缺少的任何线索.
在“父级”和“父级”中都填充了所有对应的PK.子表按照提供的顺序进行,但是在子表中FK设置为​​null

家长班:

@Entity
@Table(name = "DIVERSITY_TEMPLATE")
public class DiversityTemplate implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @SequenceGenerator(name = "DIVERSITY_TEMPLATE_ID", sequenceName = "DIVERSITY_TEMPLATE_ID", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "DIVERSITY_TEMPLATE_ID")
    @Column(name = "DIVERSITY_TEMPLATE_ID")
    private Integer diversityTemplateId;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "diversityTemplate", fetch = FetchType.LAZY)
    private List<DiversityTemplateAttribute> attributes = new ArrayList<>();

儿童班:

@Entity
@Table(name = "DIVERSITY_TEMPLATE_ATTRIBUTE")
@TypeName("DiversityTemplateAttribute")
public class DiversityTemplateAttribute implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @SequenceGenerator(name = "DIVERSITY_TEMPLATE_ATTR_ID", sequenceName = "DIVERSITY_TEMPLATE_ATTR_ID", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "DIVERSITY_TEMPLATE_ATTR_ID")
    @Column(name = "DIVERSITY_TEMPLATE_ATTR_ID")
    private Integer diversityTemplateAttributeId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "DIVERSITY_TEMPLATE_ID", nullable=false, referencedColumnName = "DIVERSITY_TEMPLATE_ID")
    private DiversityTemplate diversityTemplate;

服务等级:

 diversityTemplateRepository.save(diversityTemplate);

样本json

{
  "diversityTemplateId": 0,
  "attributes": [{
    "diversityTemplateId": 0,
    "diversityTemplateAttributeId": 0,
  }, {
    "diversityTemplateId": 0,
    "diversityTemplateAttributeId": 0,
  }]
}

请提出建议.

最佳答案
通常,空FK列仅来自设置关系的一侧.

我想你有以下

DiversityTemplate diversityTemplate = ...
diversityTemplate.getAttributes().add(...)
...
diversityTemplateRepository.save(diversityTemplate);

这是错误的,因为多样性模板属性不了解父级,只有父级才知道其子级.

解决这个问题很容易,您必须在子级中设置父级引用.

diversityTemplateAttribute.setDiversityTemplate(diversityTemplate);

或者,您可以将此逻辑放入DiversityTemplate中的方法中,该方法会自动将属性添加到列表集的反向引用中.

转载注明原文:java-@OneToMany映射JPA中的父ID为null - 代码日志