Now we’re going to make sure the Person knows the Company for which it works. This is the “one” side of a one to many relationship. We need to explicitly set this value and map it. We also need to update the Company @OneToMany relationship so that the Entity Manager knows it is a bi-directional relationship rather than just two unidirectional relationships.
First we need to update Person:
Person.java
Next, we’ll change Company to maintain both sides of the relationship:
Before going any further, make sure all of your tests still run green.
We are now adding and removing Person objects from collections. To make this work, we need to add an equals() method and a hashCode() method to the Person class:
Finally, we’ll update CompanyTest in several stages:
First, add a utility method to retrieve companies by name:
Add another support method to create a company and hire a few people:
The method createCompany used to directly lookup a company by name. Update the test method to use this private method by changing this line:
to:
Update the method createCompanyAndHirePeopl by using the support method createCompanyWithTwoEmployees():
Finally, add an additional unit test to hire and fire people:
Comments