Mapping Help of OneToOne with Lazy Loading and Single call to save


#1

Here is the details of problem statement:

Entities:
Employee
Address
Relations

Now, what I need is that:

  1. There should be OneToOne Mapping between Entities.
  2. Primary Key (and Foreign Key) are manually generated. I don’t this automatically generated.
  3. I create Employee and Address object, setup required fields and set just address in employee (not employee in address) employee.setAddress(address).
  4. When persisting employee object, it should save employee, and address and setup FK relation in Address table with Employee. I don’t need to save Address separately.
  5. Next, while retrieving data, I would like when getting Employee, Address should be lazily loaded.
  6. Also, another important point is Address field is optional wrt Employee. I mean, Every address will have exactly one Employee, but not all Employee will have address.

#2

Okay I figured out, most of the things. My only problem remains is that I need to set Employee to address and address to employee. Only then both persist on persisting employee.
If I don’t set address.setEmployee(employee);
I get attempted to assign id from null one-to-one property [com.mohit.learn.entity.Address.employee]


#3

Yes, you need to set both sides if this is a bidirectional association and you rely on cascade.


#4

Thanks Vlad! Finally figured out solution.


#5

You are very welcome.