Error in Entity Mapping in SpringBoot JPA. Entities are creating but foreign_key is not added

I am learning SpringBoot and for that I tried to implement what I have learned with the help of a Problem.

This is the basic question: We have 2 entities:

Team: id, name Developer: id, team_id, name, phone number

Create team API : This api takes in a team and a list of developers to be mapped with this team, and is expected to create the corresponding entries in the database.
Sample request: {"team": {"name": "claims"}, "developers": [{"name": "someone", "phone_number": "9999999999"}, {"name": "somebody", "phone_number": "9111111111"}]}

I used these entities:

**Employee.java**
package com.PagerDuty.PagerDutyManager.Employee;

import com.PagerDuty.PagerDutyManager.Team.Team;
import com.fasterxml.jackson.annotation.JsonBackReference;

import javax.persistence.*;
import javax.validation.constraints.*;

@Entity
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotNull
    @NotBlank(message="Invalid Name")
    private String name;

    @Column(columnDefinition="varchar(10)", unique = true)
    @NotBlank(message = "Phone_number Number Required!")
    @Pattern(regexp="(^$|[0-9]{10})", message="Invalid Phone_number Number")
    private String phone_number;

    @ManyToOne
    @JoinColumn(referencedColumnName = "id")
    @JsonBackReference
    private Team team;

    public Employee(){}

    public Employee(Long id,
                    @NotNull @NotBlank(message = "Invalid Name") String name,
                    @NotBlank(message = "Phone_number Number Required!") @Pattern(regexp = "(^$|[0-9]{10})", message = "Invalid Phone_number Number") String phone_number, String teamId) {
        this.id = id;
        this.name = name;
        this.phone_number = phone_number;
        this.team = new Team(teamId, "");
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone_number() {
        return phone_number;
    }

    public void setPhone_number(String phone_number) {
        this.phone_number = phone_number;
    }

    public Team getTeam() {
        return team;
    }

    public void setTeam(Team team) {
        this.team = team;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", phone_number='" + phone_number + '\'' +
                ", team=" + team +
                '}';
    }
}
**Team.java**
package com.PagerDuty.PagerDutyManager.Team;

import com.PagerDuty.PagerDutyManager.Employee.Employee;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;

import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.List;

@Entity
public class Team {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotNull
    @NotBlank(message="Invalid Name")
    @Column(unique = true)
    private String name;

    @OneToMany(cascade=CascadeType.ALL, mappedBy = "team")
    private List<Employee> employees;

    public Team(){}

    public Team(String id,
                @NotNull @NotBlank(message = "Invalid Name") String name) {
        this.id = Long.parseLong(id);
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Employee> getEmployees() {
        return employees;
    }

    public void setEmployees(List<Employee> employees) {
        this.employees = employees;
    }

    @Override
    public String toString() {
        return "Team{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", employees=" + employees +
                '}';
    }
}

I have done the above sample request, but cant establish the relation.

Employees are added successfully while adding the team. Add team: Here RequestBody is to handle the body properly. // Please suggest a better way of doing the requestBody Structure Handling```

**AddTeam Controller Function**
@PostMapping("/team")
    public void addTeam(@RequestBody RequestCustomBody body){
        System.out.println("Add team request body "+body.toString());
        Team team = body.getTeam();
        team.setEmployees(body.getDevelopers());
        System.out.println("New Team "+team.toString());
        teamService.addTeam(team);
    }

**AddTeam Service Function**
public void addTeam(Team team){
        teamRepository.save(team);
    }

But I am only getting Employee and Team added but no foreign key addition.

Anyone pls help me what am I doing wrong. And also tell a good way of doing the things.


You need to do body.getDevelopers().forEach(d -> d.setTeam(team)).

Why? The Employee is, in JPA terminology, the owning side of the relationship. This is counter-intuitive (as in everyday usage one can say "a team has employees"). But in JPA the owning side is (simplifying here) the one that has the foreign key (exception when using a relation table). The other side, the reverse, is the one that has the mappedBy property in the relationship annotations.

Bottom line, you need to set the relationship from the owning side in JPA. You could even skip setting team.employees and, from the perspective of the database, the effect would be the same.