layout | title | permalink |
---|---|---|
page |
401.18 Reading Notes |
/401-R18/ |
-
In Spring MVC, Many-to-many relationships are established with the annotation
@ManyToMany
-
For an SQL database, a join table must be created that includes the respective values used to relate the resources.
-
Within the related Java classes, one will define the join table with
@JoinTable
annotation and accompanying code block which defines the name of the relational table as well as the respective properties to be included. The class including this annotation with be the joinColumn resource, while the other will be the inverseJoinColumn resource
First related class:
@Entity
@Table(name = "Employee")
public class Employee {
// ...
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(
name = "Employee_Project",
joinColumns = { @JoinColumn(name = "employee_id") },
inverseJoinColumns = { @JoinColumn(name = "project_id") }
)
Set<Project> projects = new HashSet<>();
// standard constructor/getters/setters
}
Second related class:
@Entity
@Table(name = "Project")
public class Project {
// ...
@ManyToMany(mappedBy = "projects")
private Set<Employee> employees = new HashSet<>();
// standard constructors/getters/setters
}