I have 2 entities/model. Department and Employee
Relationship is 1 Department has MANY Employee.
My understanding of how to go about implementing a Bi-directional relationship of entities is:
- Identify the Parent and Child
- Identify the owner of relationship (in this case, DepartmentownsEmployee). Then addmappedBy='fieldname'
- Annotate the both entities with inverse. @OneToManyon 1st entity and@ManyToOneon the 2nd entity
Below is how I designed the app.
Model
Department
@Entity
public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String departmentName;
    @OneToMany(mappedBy = "department")
    private Set<Employee> employees;
    //getters and setters...
}
Employee
@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String middleName;
    private String lastName;
    @ManyToOne
    @JsonIgnore
    private Department department;
}
Now, if I GET department by id (e.g. localhost:8080/department/1)
I'll get :
{
    "id": 1,
    "departmentName": "Accounting",
    "employees": [
        {
            "id": 1,
            "firstName": "John",
            "middleName": "Johnny",
            "lastName": "Doe"
        }
    ]
}
which is fine because I can see the Employee(s) who belongs to a specific Department.
However, on the employee side, if I GET employee by id (e.g. localhost:8080/employee/1)
I would get a json result which only displays the employee name BUT does NOT include the Department where the Employee belongs.
{
    "id": 1,
    "firstName": "John",
    "middleName": "Johnny",
    "lastName": "Doe"
}
I had to add @JsonIgnore to department field in Employee class to avoid stackoverflow/endless nested json serialization when doing a GET department (e.g. localhost:8080/department/1)
I have 2 questions :
- How do I also display the department information when doing a GET employee by id?
- Do I need to create a custom query in the Repository interface using @Queryinstead? At least for the purpose of displaying theDepartmentname along withEmployeewhen I do a GETEmployeeby id?
Thank you.
 
    