How to save an external key object in JPA

I have 2 customer tables and customerhistory. customhistory has a foreign key customerId, which refers to the customer customerId. In the Entity that the JPA generated, I have a customer object in the customerhistory class, whereas I want to save only customerId in the customerhistory table

I get the correct customerId, but when I want to keep the customerId attribute, I only have the customer object with me, but there is no customerId in the class of auto-generated consumerhistory objects

@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 do not have clientId with me in the customerHistory entity. How to save it?

+7
source share
3 answers

Use the getReference call entityManager to load the client object using the identifier, and then set it to the client history. In most cases, this call returns a proxy with only a built-in id; client attributes will not be loaded unless any other client method is called.

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

The relationship between your tables is controlled by JPA, you should not access customerId in customerHistory. You must use customer.getHistory () (or whatever you called it) to manipulate related stories. Referential integrity will be managed by the JPA.

+2
source

If you use eclipseLink as a JPA provider, there is an annotation that is implemented to update the associated attribute, set it before the class as follows:

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

All Articles