2013-05-15 20 views
7

我有2個表客戶和客戶歷史。 customhistory具有引用客戶customerId的外鍵customerId。在由JPA生成的實體中,我在customerhistory類中有一個客戶對象,而我只想在consumerhistory表中保存customerId如何在JPA中保存外鍵實體

我得到正確的customerId,但是當我想保存屬性customerId時,我只有客戶與我的對象,但在自動生成的實體類的consumerhistory

@Entity 
public class Customerhistory implements Serializable { 
    private static final long serialVersionUID = 1L; 

    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO) 
    private int primarykeyId; 

    //bi-directional many-to-one association to Customer 
    @ManyToOne 
    @JoinColumn(name="CustomerId") 
    private Customer customer; 

沒有客戶ID如上圖所示,我不以實體customerHistory有客戶ID和我在一起。如何保存?

回答

17

使用entityManager的getReference調用來使用id加載客戶對象,然後將其設置到客戶歷史記錄上。在大多數情況下,這個調用會返回一個只有嵌入ID的代理,除非客戶的其他方法被調用,否則客戶屬性將不會被加載。

Customer customer = entityManager.getReference(Customer.class, cutomerId); 

CustomerHistory newCustomerHistory = new CustomerHistory(); 
newCustomerHistory.setCustomer(customer); 
entityManager.persist(newCustomerHistory); 
+0

我可以在一個單一的做到這一點交易? – Ced

+0

是的,你可以在單個交易中完成。 – Ced

2

您的表之間的關聯由JPA管理,您不應訪問customerHistory中的customerId。您應該使用customer.getHistory()(或任何您稱之爲的)來操縱關聯的歷史記錄條目。參考完整性將由JPA管理。

0

如果您正在使用的EclipseLink作爲JPA提供有是實現刷新相關的屬性,如下班前設置註釋:

@Cache(alwaysRefresh = true, disableHits = true) 
public class TheMainEntity { 
    ... 
    ... 
    ... 
    ... 
}