我有两个实体Product和Order,每当创建订单时,我都会更新产品的order_id我尝试应用乐观锁,以便在获取产品以检查其orderId是否为空,然后用新的orderId更新orderId的过程中,没有其他线程通过。2我如何通过@Transaction和@Version来确保这一点呢?3甚至更新查询也没有改变版本。4我是否应该为版本控制做一些模式上的改变呢?
订单存储库
@Modifying
@Transactional
@Query("Update ProductEntity p set p.orderId = :orderId " +
"where p.productId = :productId")
void updateProductByOrderId(Long orderId, Long productId);
@Data
@Builder
@Entity
@NoArgsConstructor
@AllArgsConstructor
@DynamicUpdate
// @Table
public class ProductEntity {
public ProductEntity(String brandName, double price) {
this.brandName = brandName;
this.price = price;
}
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long productId;
@Column
private String brandName;
@Column
private Double price;
@Nullable
@Column(name = "fk_order_id")
private Long orderId;
@Version
@Column(name = "version")
private Long version;
@Transactional
public OrderEntity createOrder(OrderReq orderReqBody) throws Exception {
List<ProductEntity> productList = new ArrayList<>();
for (long id : orderReqBody.getProductIdList()) {
ProductEntity productEntity = this.productRepository.findById(id).get();
if (productEntity.getOrderId() != null) {
throw new Exception("one or more product(s) are unavailable");
}
productList.add(productEntity);
}
OrderEntity toSave = OrderEntity.builder()
.amount(orderReqBody.getAmount())
.createdAt(LocalDateTime.now())
.build();
OrderEntity orderEntityDB = this.orderRepository.saveAndFlush(toSave);
for (ProductEntity p : productList) {
this.productRepository.updateProductByOrderId(orderEntityDB.getOrderId(), p.getProductId());
// i am attaching a debuggger at this line and
running an update query via workbench,
still the version remains the same and both are able to update.
return orderEntityDB;
}
1条答案
按热度按时间zlhcx6iw1#
您的查询不更新Version列是有道理的;您没有在更新查询中设置它。您可以在查询中添加逻辑来增加版本,但我推荐一种不同的方法。
由于您已经有了在方法中检索的产品实体的列表,请修改for循环以更新实体的orderId并直接保存实体。