簡體   English   中英

如何在JPA中保存外鍵實體

[英]how to save foreign key entity in JPA

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

我正在獲得正確的customerId,但是當我想保存屬性customerId時,我只有客戶的對象,但是我自己生成的實體類中沒有customerId

@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;

如上所示,我在實體customerHistory中沒有customerId。 怎么保存呢?

使用entityManager的getReference調用使用id加載客戶對象,然后將其設置到客戶歷史記錄中。 在大多數情況下,此調用將返回僅嵌入了id的代理,除非調用客戶的其他某些方法,否則不會加載客戶屬性。

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

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

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

如果您使用eclipseLink作為JPA提供程序,則會生成一個用於刷新關聯屬性的注釋,在類之前將其設置如下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM