2013-04-10 34 views
0

我有一個名爲'訂單'的JPA實體。當一個訂單被「更新」(複製時只有很小的改動),我會在「更新」訂單中存儲對原始訂單的參考。我可以使用什麼JPA命名查詢來訪問ManyToMany連接?

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方法來訪問續訂訂單列表:

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,該查詢返回,而不是它的更新的訂單訂單本身。

回答

1

,結束了對我的工作的查詢:

select r from Order o left outer join o.renewedOrders r where o.id =:orderId