Parent Id null in @OneToMany mapping JPA

后端 未结 2 431
栀梦
栀梦 2021-01-06 08:20

I am using javax.persistence.OneToMany relationship in a Parent Child relationship. The parent Id is coming as null, I have read through all the related post in Stackoverflo

2条回答
  •  暖寄归人
    2021-01-06 08:34

    Usually empty FK columns are coming from setting only one side of the relation.

    I imagine you have the following

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

    This is wrong because the DiversityTemplateAttribute doesn't know about the parent, only the parent know about his children.

    Solving this is easy, you have to set the parent reference in the child.

    diversityTemplateAttribute.setDiversityTemplate(diversityTemplate);
    

    Or you can put this logic into a method within the DiversityTemplate which automatically adds the attribute into the List + sets the backreference.

提交回复
热议问题