Parent Id null in @OneToMany mapping JPA

后端 未结 2 412
栀梦
栀梦 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:27

    I know it's too late but you can also do...

    Parent Class:

    @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, fetch = FetchType.LAZY)
        @JoinColumn(name = "DIVERSITY_TEMPLATE_ID")
        private List attributes = new ArrayList<>();
    

    Child Class:

    @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)
        private DiversityTemplate diversityTemplate;
    

    Service Class:

    diversityTemplateRepository.save(diversityTemplate);
    

    This way you DON'T NEED TO DO PARENT ENTRY IN EACH CHILD. it will do by itself. you just need to save parent that's it.

    Quick steps what I did.

    1. Removed mappedBy from Parent.
    2. Added @JoinCollumn foreign key in Parent
    3. Removed @JoinCollumn from Child.

    Hope it helps.

提交回复
热议问题