Hibernate在外部事务类中从getCurrentPrice返回null。
但是,新的get by id调用会返回当前价格正常的产品。
该如何解决?
这是我的产品类别
@Table(name = "products")
public class Product {//...
@OneToMany(mappedBy = "product", fetch = FetchType.LAZY)
private Set<OrderItem> orderItems = new HashSet<>();}
和OrderItem
@Table(name = "orderItems")
public class OrderItem extends BaseModel {//...
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "productId")
private Product product;
@Column
private double currentPrice;
}
还有DAO
@Repository
@Transactional
public class HibernateOrderDao {//...
public Serializable save(Order order) {
order.getReceiver().getOrdersToReceive().add(order);
order.getItems().forEach(item -> {
item.setOrder(order);
item.getProduct().getOrderItems().add(item);//todo improve by direct sql or...!
});
order.getAddresses().forEach(address -> address.getOrders().add(order));
return super.save(order);
}
但是在外部事务方法中,getCurrentPrice返回null
private Double calculateItemsCost(final OrderItem item) {
return item.getProduct().getCurrentPrice()
* item.getQuantity();
}
答案 0 :(得分:1)
如果您可以看到产品ID,请尝试先致电Product product = productService.findById(item.getProduct().getId())
,然后再致电item.setProduct(product)