Understanding Entity Modeling using 3 models in Hibernate

Viewed 39

I am starting to learn Spring Boot and Hibernate by building small rest services. I am using MySQL as my database. I am able to understand relationship annotation used in hibernate though sometimes it's tricky to write with all the verbose syntax.

Right now I am struggling with how to map 3 entities together. The following is what I am trying to achieve. I have a teacher entity, a grade entity, and a section entity. Now, each Grade can have multiple sections.

public class Grade {
   private String name;

   @OneToMany
   private List<Section> sections;
}

public class Section {
   private String name;
}

And, a teacher can teach in multiple grades or multiple sections of the same grade.

Imagine grade 1 to 5, each grade has section A to D.

Teacher, let's say John can teach Grade 1 (sec A, B) and Grade 2 ( sec C, D).

I am failing to understand the syntax to implement the above relationhip. One way is to use another Entity called Class which will have grade and section as property.

public class Class {
   private Grade grade;
   private Section section;
}

another way can be to use a map data structure like Map<Grade, List<Section>> class;

Still, I am looking for help to write it down with JPA annotations. Any lead is appreciated.

1 Answers

First of all I want to mention that your question is not specific to Hibernate, as you can solely rely on the JPA Specification for this task. However, Hibernate is the default ORM for Spring and will implement the JPA spec in your program by default.

Second, I do not think that you need separate database tables for Section and Grade, and they could be modeled as simple Java Enums. In the following I made a quick sketch of a class diagram (not DB Model!) that came to my mind.

class-diagram

Note that Grade and Section are Enums, to restrict entering corrupted values. In the database the Grade and Section object can be mapped as either ordinal or String, see here for reference. I would recommend persisting as String by using this annotation @Enumerated(EnumType.STRING). With regard to mapping the one to many relationship between teacher and class, I would recommend a bidirectional relation such as shown here. However, note that there are multiple ways to model this relationship in JPA. I hope I was able to help. Good luck!

Related