【问题标题】:Saving parent and child on a single json POST [duplicate]在单个json POST上保存父母和孩子[重复]
【发布时间】:2019-05-04 21:04:05
【问题描述】:

我正在开发一个电子商务平台。我有一个“Product”实体作为父实体,“Pimage”实体作为子实体。

我有两个实体的 CrudRepository。

实体以这种方式建模:

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> {

}

现在,如果我发送这样的 PUT 请求:

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

我可以在数据库中看到 Product 实体已保存,Pimage 实体也已保存,但 PImage 实体的“productid”值为 null。

如何将 productid 保存在 Pimage 实体的“productid”字段中?

如果我尝试用这样的方法手动执行,一切正常,并且 PImage 的 productid 字段设置正确:

    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);

提前谢谢你。

【问题讨论】:

    标签: java spring spring-data-jpa spring-data-rest


    【解决方案1】:

    为了帮助有同样问题的人,Alan Hay 提供了一个链接,指向我的问题的一个可能副本,我在其中找到了一个与我有同样问题的人,并提供了解决方案:

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

    在双向关联中,您需要手动设置父 ID。

    谢谢艾伦·海。

    最好的问候。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 2014-10-27
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      相关资源
      最近更新 更多