Schema design
Q How to read relationships in schema design ?
One To Many Relationship
Take an example :: Mother and Child
Mother Side
1 mother can have one children only ? ❌
1 mother can have many children? ✅
1 mother -> many child
here we find child (many).
Child Side
1 child can be associated with many mothers ? ❌
1 child can be associated with one only mother ? ✅
1 child -> one mother
here we find mother (one)
Result
mother (one) --child (many).
Annotations
Fk :: annotation @ManyToOne (child side)
inverse side :: annotation @OneToMany (mother side)
CODE :: ONE TO MANY 🌈
/* ==== Child (FK Side) ===== */
public class Child {
@ManyToOne
@joinColumn(name="mother_id")
private Mother motherRef;
}
/* ==== Mother (Inverse Side) ===== */
// annotation tells the hibernate fetch the related child for "motherRef"
// So it will see the motherRef inside Child class and
// and fetch lazyly when getter is called (fetch on demand) as by default
// @OneToMany is Lazy Fetch
public class Mother {
@OneToMany(mappedBy="motherRef")
List<Child> child = new ArrayList<>();
}
CODE :: ONE TO MANY EXPLAIN (Contd ..)

Many To Many Relationship
Take an example :: Course and Student Relationship
Course Side
1 Course is enrolled by one student only ? ❌
1 Course can be enrolled by one many students ? ✅
1 Course -> many Students
here we find students side (many)
Student Side
1 student can be enrolled in one course only ? ❌
1 student can be enrolled in many courses ? ✅
1 Student -> many Courses
here we find Course side (many)
Hence the resultant is many to many relationship
CODE :: MANY TO MANY 🌈
Remove Circular dependency in your controller class in manyToMany case
i.e User.getRoles().setUsers(null); and vice versa
/* ==== Role Side ===== */
public class Role {
@ManyToMany(
fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH
})
@JoinTable(
name = "course_student", // joinTableName
joinColumns = @JoinColumn(name = "role_id"), // fk_this_Table
inverseJoinColumns = @JoinColumn(name = "user_id") // fk_inverse_Table
)
private List<User> users = new ArrayList<>(); // inverse_Table_List
}
/* ==== Role Side ===== */
public class User {
@ManyToMany(
fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH
})
@JoinTable(
name = "course_student", // joinTableName
joinColumns = @JoinColumn(name = "user_id"), // fk_this_Table
inverseJoinColumns = @JoinColumn(name = "role_id") // fk_inverse_Table
)
private List<Role> users = new ArrayList<>(); // inverse_Table_List
}
Last updated