java 如何在JPA中保存外键实体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16572207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to save foreign key entity in JPA
提问by curious
I have 2 tables customer and customerhistory. customhistory has foreign key customerId which is referencing to customer's customerId. In the Entity that is generated by JPA i have a object of customer in customerhistory class whereas i want to save only customerId in consumerhistory table
我有 2 个表 customer 和 customerhistory。customhistory 有外键 customerId,它引用客户的 customerId。在由 JPA 生成的实体中,我在 customerhistory 类中有一个客户对象,而我只想在消费者历史表中保存 customerId
I am getting the correct customerId but when i want to save the attribute customerId i have only the object of customer with me but no customerId in autogenerated entity class of consumerhistory
我得到了正确的 customerId,但是当我想保存属性 customerId 时,我只有 customer 的对象,但在消费者历史的自动生成的实体类中没有 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;
As shown above i dont have customerId with me in entity customerHistory . how to save it?
如上所示,我在实体 customerHistory 中没有 customerId 。如何保存?
回答by gkamal
Use the getReferencecall of the entityManager to load customer object using the id and then set that onto the customer history. In most cases this call would return a proxy with just the id embedded, the customer attributes will not be loaded unless some other method of the customer is invoked.
使用entityManager的getReference调用使用 id 加载客户对象,然后将其设置到客户历史记录中。在大多数情况下,此调用将返回一个仅嵌入 id 的代理,除非调用客户的某些其他方法,否则不会加载客户属性。
Customer customer = entityManager.getReference(Customer.class, cutomerId);
CustomerHistory newCustomerHistory = new CustomerHistory();
newCustomerHistory.setCustomer(customer);
entityManager.persist(newCustomerHistory);
回答by stacker
The association between your tables is managed by JPA you're not supposed to access the customerId in customerHistory. You should use customer.getHistory() (or whatever you called it) to manipulate the associated history entries. The referential integrity will be managed by JPA.
您的表之间的关联由 JPA 管理,您不应访问 customerHistory 中的 customerId。您应该使用 customer.getHistory()(或您称之为的任何名称)来操作相关的历史记录条目。参照完整性将由 JPA 管理。
回答by E_X
If you are using eclipseLink as a JPA provider there is an annotation that is implemented to refresh the associated attribute, set it before the class as follows:
如果您使用 eclipseLink 作为 JPA 提供程序,则实现了一个注释以刷新关联的属性,将其设置在类之前,如下所示:
@Cache(alwaysRefresh = true, disableHits = true)
public class TheMainEntity {
...
...
...
...
}