【发布时间】:2019-02-24 15:50:44
【问题描述】:
我有一个对象,其中包含我似乎无法正确更新的其他对象列表。我可以用对象列表(ProductItemQuantity)创建对象(产品)没问题。我也可以对对象列表进行 PUT,但它会创建一个新的对象列表,我所做的一切都是 PUT。我希望更新我提供的对象列表,而不是在每次放置父对象时都创建一个新列表。
如果我向 ProductItemQuantity 添加一个 ID,我会得到一个异常:
detached entity passed to persist
这是我的课程:
Product.java
@Entity
public class Product {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@ManyToOne
private Organization org;
private String barCode;
private String name;
@ManyToOne(cascade=CascadeType.MERGE)
private Status status;
@ManyToMany(cascade=CascadeType.MERGE)
private List<Fee> fees;
@ManyToMany(cascade=CascadeType.ALL)
private List<Note> notes;
@ManyToMany(cascade=CascadeType.ALL)
private List<ProductItemQuantity> productItems;
private Integer stock;
private BigDecimal msrp;
@CreationTimestamp
private LocalDateTime createdOn;
@UpdateTimestamp
private LocalDateTime updatedOn;
// Getter & Setters
ProductItemQuantity.java
@Entity
public class ProductItemQuantity {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private Integer count;
@ManyToOne
private ProductItem productItem;
@CreationTimestamp
private LocalDateTime createdOn;
@UpdateTimestamp
private LocalDateTime updatedOn;
// Getters / setters
ProductItem.java
@Entity
public class ProductItem {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@ManyToOne
private Organization org;
@ManyToOne
private Supplier supplier;
private String barCode;
private String description;
private String name;
private Integer stock;
private Integer caseQty;
private BigDecimal caseCost;
@ManyToMany(cascade=CascadeType.ALL)
private List<Note> notes;
@CreationTimestamp
private LocalDateTime createdOn;
@UpdateTimestamp
private LocalDateTime updatedOn;
ProductController.java
@PutMapping("/{id}")
public Product update(@RequestBody Product product, @PathVariable long id) {
Product savedProduct = productService.save(product);
return savedProduct;
}
工作 CRUD PUT 请求:http://localhost:8080/product/1
{
"barcode":"12347163",
"name":"Product 1",
"stock": 12,
"msrp": 29.99,
"org": {
"id":1
},
"status":{
"id":1
},
"productItems":[{
"count":30
},{
"count":30
}
],
"fees":[{
"id":1
},{
"id":2
}],
"notes":[{
"title":"Product Created",
"description":"Note created by user X on 12/16/2019 11:00PM"
},{
"title":"Product Updated",
"description":"Product updated stock by user X on 12/16/2019 11:00PM"
}]
}
CRUD PUT 请求中断:http://localhost:8080/product/1
{
"barcode":"12347163",
"name":"Product 1",
"stock": 12,
"msrp": 29.99,
"org": {
"id":1
},
"status":{
"id":1
},
"productItems":[{
"id":1,
"count":30
},{
"id":2,
"count":30
}
],
"fees":[{
"id":1
},{
"id":2
}],
"notes":[{
"title":"Product Created",
"description":"Note created by user X on 12/16/2019 11:00PM"
},{
"title":"Product Updated",
"description":"Product updated stock by user X on 12/16/2019 11:00PM"
}]
}
【问题讨论】:
标签: java spring-boot jpa spring-data-jpa crud