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
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
@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?
Use the getReference call 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.
Customer customer = entityManager.getReference(Customer.class, cutomerId);
CustomerHistory newCustomerHistory = new CustomerHistory();
newCustomerHistory.setCustomer(customer);
entityManager.persist(newCustomerHistory);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With