如何在JPA中保存外键实体

cur*_*ous 9 java database hibernate 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;
Run Code Online (Sandbox Code Playgroud)

如上所示,我在实体customerHistory中没有customerId.怎么保存呢?

gka*_*mal 21

使用entityManager 的getReference调用使用id加载客户对象,然后将其设置到客户历史记录中.在大多数情况下,此调用将返回仅嵌入了id的代理,除非调用客户的其他某些方法,否则不会加载客户属性.

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

CustomerHistory newCustomerHistory = new CustomerHistory();
newCustomerHistory.setCustomer(customer);
entityManager.persist(newCustomerHistory);
Run Code Online (Sandbox Code Playgroud)