Search code examples
springdatabasespring-data-jpapersistenceh2

Spring Data JPA save child object with the ID of parent object


I have two objects, one parent and one child as follows :

@Entity
@Table(name="category")
public class CategoryModel {
    private @Id @GeneratedValue Long id;

    private String name;

    @OneToMany(mappedBy="category", cascade=CascadeType.PERSIST)
    private List<AttributeModel> attributes;
}

@Entity
@Table(name="attribute")
public class AttributeModel {
    private @Id @GeneratedValue Long id;

    private String name;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="category_id")
    private CategoryModel category;
}

I also have dtos which maps to these model objects but I ommited them. When I try to save a category object with this payload Attribute values are also created in the attribute table but with null category ids.

{
    "name":"Chemicals",
    "attributes":[
        {"name": "volume"}, {"name":"humidity"}
    ]
}

What can I do to have my attribute values persisted into the database with the category id which is created before them?


Solution

  • I solved this by manually setting child object's reference to the parent object as follows :

    public Long createCategory(CategoryDto categoryDto) {
        CategoryModel categoryModel = categoryDto.toModel(true,true);
        categoryModel.getAttributes().forEach(a -> a.setCategory(categoryModel));
        return categoryRepository.save(categoryModel).getId();
    }