Home > OS >  How to create with JPA foreignkey at 'One' side table OneToMany
How to create with JPA foreignkey at 'One' side table OneToMany

Time:03-18

I have two class Employee and Email with relational OneToMany & ManyToOne.

How to create / generate with JPA table, foreignkey column ex:(email_id) at Employee table ?

this is image ERD Table Employee(OneToMany) & Email

@Entity
@Data
public class Employee {
@Id
private Long id;
private String name;
private String address;
@OneToMany
private List<Email> emailList;
}

@Entity
@Data
public class Email {
@Id
private Long id;
private String email;
@ManyToOne
private Employee employee;
}

CodePudding user response:

The design is incorrect, a foreign key should always be present on the many side in a one to many relationship. One employee can have many emails. Many is on the email side. One email is associated with one employee only.

Think about it, if an employee has many emails, how this will be presented in the table Employee? in the design provided, there will be duplicate entries for an employee with just the email_id which will be different.

But if it is the other way around, employee_id in the table Email. There will be multiple different entries for email and each entry will be associated with a specific employee.

Therefore email_id should not be present in Employee instead employee_id should be in the table Email.

CodePudding user response:

You add @JoinColumn(name="employee _id", nullable=false) in your Email class as:

@Entity
@Data
public class Employee {
...
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "employee")
private List<Email> emailList;
}

@Entity
@Data
public class Email {
...
@ManyToOne
@JoinColumn(name="employee_id", nullable=false)
private Employee employee;
}

Nb : By design the foreign key will be present just in Email table

  • Related