spring-boot - org.springframework.transaction.TransactionSystemException:无法提交 JPA 事务;嵌套异常是 javax.persistence.RollbackException
问题描述
这是我的 orderservice 实现,用于在此处使用 customerid 创建和保存订单,我正在获取客户和客户有一个购物车,并且在购物车产品列表中,对于该产品列表,我应该创建一个订单。
public Order save(int custid) {
Optional<Customer> cust = customerRepo.findById(custid);//here customer is there and inside customer cart is there inside cart medicine list is there.
Cart ct= cust.get().getCart();//getting cart from customer
if(ct.getMedicineList().size()!=0) {//create order only if the medicine list is not empty. there are 8 fields **orderDate,dispatchDate,status,medicineList,totalCost,customer and orderId(GeneratedValue)** I can't set the orderId cuz it is auto generated.
LocalDate todaysDate = LocalDate.now();
LocalDate dispatchdate = todaysDate.plusDays(3);
List<Medicine> orderList= new ArrayList<Medicine>();
List<Medicine> cartList= new ArrayList<Medicine>();
cartList=ct.getMedicineList();
orderList.addAll(cartList);
Order ord = new Order();
ord.setCustomer(cust.get());
ord.setMedicineList(orderList);
ord.setDispatchDate(dispatchdate);
ord.setOrderDate(todaysDate);
ord.setStatus("Placed");
ord.setTotalCost((float)ct.getTotalAmount());
logger.info("Add order to the database");
return orderRepository.save(ord);
}
return null;
}
这是我的订单控制器
@PostMapping("/order/{custid}")
public ResponseEntity<Order> addOrder(@Valid @PathVariable("custid") int custid) {
logger.info("Add order in database");
return new ResponseEntity<>(orderService.save(custid), HttpStatus.OK);
}
这是我的药实体
@Data
@RequiredArgsConstructor
@ToString
@Table(name = "medicine")
@Entity
public class Medicine {
@Id
@Column(name = "medicine_id", nullable = false)
@NonNull
@GeneratedValue
private int medicineId;
@NonNull
@Size(min = 3, message = "Minimum charecters in medicine name should be 3.")
@NotEmpty
@Column(unique = true, name = "medicine_name", nullable = false)
private String medicineName;
@NonNull
@Column(name = "medicine_cost", nullable = false)
private float medicineCost;
@NonNull
@Column(name = "mfd", nullable = false)
private LocalDate mfd;
@NonNull
@Column(name = "expiry_date", nullable = false)
private LocalDate expiryDate;
@NonNull
@Column(name = "medicine_quantity", nullable = false)
private int medicineQuantity = 1;
@NonNull
private String medicineCategory;
@NonNull
private String medicineDescription;
@JsonIgnore
@ManyToMany(cascade = CascadeType.ALL, mappedBy = "medicineList",fetch = FetchType.EAGER)
private List<Order> orderList;
}
这是我的订单实体
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Order {
@Id
@Column(name = "orderId")
@GeneratedValue
private int orderId;
@NonNull
private LocalDate orderDate;
@ManyToMany(targetEntity = Medicine.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "ord_med", joinColumns = { @JoinColumn(name = "ord_id") }, inverseJoinColumns = {
@JoinColumn(name = "med_id") })
private List<Medicine> medicineList = new ArrayList<>();
@NonNull
private LocalDate dispatchDate;
@NotEmpty
private float totalCost;
@NonNull
private String status;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="c_ord_fk",referencedColumnName = "customerId")
@NonNull
private Customer customer;
}
在这里,当我尝试为购物车内的列表创建订单时,它给了我[36m.mmaExceptionHandlerExceptionResolver[0;39m [2m:[0;39m Resolved [org.springframework.transaction.TransactionSystemException:无法提交 JPA 事务;嵌套异常是 javax.persistence.RollbackException: Error while committing the transaction] 我不确定,但我认为它是因为 id 但它是自动生成的。Idk 如何为产品列表创建订单对象,或者这是正确的方法。
解决方案
实际上我找到了答案,我所要做的就是当您使用ManyToMany映射时,级联类型必须是 cascade = {CascadeType.MERGE,CascadeType.REFRESH} 而不是 {cascade = CascadeType.ALL} 并且它工作正常。参考JPA:传递给持久化的分离实体:嵌套异常是 org.hibernate.PersistentObjectException
推荐阅读
- asp.net-core-mvc - 没有给出与“Interface.Create(Trademark, IFormFile)”所需的形式参数“photo”相对应的参数?
- apache-kafka - 是否有开源 Kafka Cassandra 连接器配置的示例?
- javascript - 如何使用扩展语法将新元素推送到 JavaScript 中的嵌套对象数组
- permissions - Rsync 未在目标目录上设置 SGID 位
- django - 如何在 django 的管理面板中存储用户提出的投诉
- java - 有没有一种方法可以让我无需在 android 中打开网站就可以在点击按钮时访问 url?
- javascript - 无法更改antd V4选择后缀图标,同时打开选项列表
- html - Django 模板:块标签
- git - 如何忽略git中的文件
- java - 为什么我在存储库上收到错误“未找到属性”?