我有一个名为“订单”的 JPA 实体。当订单被“续订”(复制了微小的更改)时,我会将对原始订单的引用存储在“续订”订单中。
JPA 实体参考:
@ManyToMany
@JoinTable(name = "OP_ORDER_RENEWAL", joinColumns = @JoinColumn(name = "ORDER_ID"), inverseJoinColumns = @JoinColumn(name = "RENEWED_ORDER_ID"))
private List<Order> renewedOrders = new ArrayList<Order>();
“更新”方法:
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public Order renewOrder(Order originalOrder) {
Order newOrder = new Order();
..............
List<Order> listOfOrdersThisOrderIsRenewing = new ArrayList<Order>();
listOfOrdersThisOrderIsRenewing.add(originalOrder);
newOrder.setRenewedOrders(listOfOrdersThisOrderIsRenewing);
em.persist(newOrder);
return newOrder;
}
每当我尝试使用 getter 方法访问 Renewed Orders 列表时:
public List<Order> getRenewedOrders() {
return renewedOrders;
}
我收到“无法延迟初始化角色集合”错误。谷歌搜索此错误后,我决定最好的选择是使用单独的 NamedQuery 来获取 RenewedOrders:
@NamedQuery(name = "Order.getRenewedOrders", query = "select o from Order o join fetch o.renewedOrders where o.id = :orderId")
当我使用该 NamedQuery 时,查询返回 Order 本身,而不是其更新的订单。