0

I'm developing an e-commerce platform. I have a "Product" entity as a parent and "Pimage" entities as childs.

I have a CrudRepository for both entities.

The entities are modelled in this way:

public class Product implements Serializable {
    private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private BigInteger id;


// ....

//bi-directional many-to-one association to Pimage
@OneToMany(cascade = {CascadeType.ALL,CascadeType.PERSIST,CascadeType.MERGE}, mappedBy="product")
private List<Pimage> pimages = new LinkedList<Pimage>();

public List<Pimage> getPimages() {
    return this.pimages;
}

public void setPimages(List<Pimage> pimages) {
    this.pimages = pimages;
}

public Pimage addPimage(Pimage pimage) {
    getPimages().add(pimage);
    pimage.setProduct(this);

    return pimage;
}

//....

public class Pimage implements Serializable {
    private static final long serialVersionUID = 1L;

    // ...

    @ManyToOne
    @JoinColumn(name="productid")
    private Product product;

    // ...



@RepositoryRestResource(exported=false)
public interface PimagesRepository extends PagingAndSortingRepository<Pimage, BigInteger> {

}

Now, if I send a PUT request like this:

{
    "description": "Description of new product",
    "title": "Title of new product",
    "price": 200,
    "pimages" : [
        {
            "path": "path to the image file"
        }
    ]
}

I can see in the db that the Product entity is saved, and the Pimage entity is saved too, but the PImage entity have the "productid" value at null.

How can I have the productid saved in the "productid" field of my Pimage entity?

If I try to do it manually with something like this, everything is ok and the productid field of PImage is correctly set:

    Product p = new Product();
    Pimage pi = new Pimage();

    p.setDescription("Description from testcase");
    p.setTitle("Title from testcase");
    p.setPrice(50f);

    pi.setPath("image path from testcase");     

    p.addPimage(pi);

    Product saved= pr.save(p);

Thank you in advance.

Mohsen
  • 4,536
  • 2
  • 27
  • 49
CSoft
  • 31
  • 1
  • 8

1 Answers1

0

In order to help people with the same problem, Alan Hay provided a link to a possibile duplicate of my question, where I found a guy who had my same exact problem, and provided the solution:

https://stackoverflow.com/a/46971491/1218425

In bidirectional associations you need to set the parent id manually.

Thank you Alan Hay.

Best regards.

CSoft
  • 31
  • 1
  • 8