【问题标题】:how to save foreign key entity in JPA如何在 JPA 中保存外键实体
【发布时间】:2013-05-10 10:44:24
【问题描述】:

我有 2 张表 customer 和 customerhistory。 customhistory 有外键 customerId,它引用了客户的 customerId。在 JPA 生成的实体中,我在 customerhistory 类中有一个客户对象,而我只想将 customerId 保存在 consumerhistory 表中

我得到了正确的 customerId,但是当我想保存属性 customerId 时,我只有 customer 对象,但在 consumerhistory 的自动生成实体类中没有 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。如何保存?

【问题讨论】:

    标签: java database hibernate jpa


    【解决方案1】:

    如果您使用 eclipseLink 作为 JPA 提供程序,则有一个用于刷新关联属性的注释,请在类之前将其设置如下:

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

    【讨论】:

      【解决方案2】:

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

      Customer customer = entityManager.getReference(Customer.class, cutomerId);
      
      CustomerHistory newCustomerHistory = new CustomerHistory();
      newCustomerHistory.setCustomer(customer);
      entityManager.persist(newCustomerHistory);
      

      【讨论】:

      • 我可以一次性完成吗?
      • 是的,您可以在单个事务中完成。
      【解决方案3】:

      您的表之间的关联由 JPA 管理,您不应该访问 customerHistory 中的 customerId。您应该使用 customer.getHistory() (或您所称的任何名称)来操作相关的历史条目。参照完整性将由 JPA 管理。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-10
        • 2011-05-01
        • 2016-08-21
        • 1970-01-01
        相关资源
        最近更新 更多