【发布时间】: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