Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to save foreign key entity in JPA

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?

like image 984
curious Avatar asked May 15 '13 18:05

curious


2 Answers

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);
like image 195
gkamal Avatar answered Sep 17 '22 17:09

gkamal


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.

like image 35
stacker Avatar answered Sep 19 '22 17:09

stacker