Search code examples
mysqlhibernatespring-mvchibernate-mappingentity-relationship

How to model relationship tables as entities in Hibernate


I'm new to using spring and hibernate. I want to design the database according to this Schema

Student, Class and School are Entities. There exists relationships studies_in(between Student and Class - one to one, with student_id and class_id as foreign keys) and belongs_to(between Class and School - many to one, with class_id and school_id as foreign keys).

Method 1:

I could have a class Student as follows:

@Entity
@Table(name="student")
public class Student {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    ...

    @OneToOne
    @JoinColumn(name="class_id")
    private Class class;
    ...

}

And similarly for the Class Entity.

Method 2:

Is this the correct way to do it or should I represent the relationship as tables, by creating them via sql queries as follows:

create table studies_in(student_id int, class_id int, 
                        primary key(student_id,class_id), 
                        foreign key(student_id) references student(id),
                        foreign key(class_id) references class(id));

And then create class for studies_in.

The previous method the relationship exists in the application level, while in this method it exists physically in the database. I feel that the second approach is better since the database would be normalised but I'm not aware of how to implement it in spring.

Please correct me if I'm wrong.

How do I proceed with it?


Solution

  • I presume that one Student can visit many classes and one class can have many students. So the correct relationship would be ManyToMany here and JoinTable usage realy makes sense.

    @ManyToMany
    @JoinTable(name="studies_in" , joinColumns={@JoinColumn(name="class_id", referencedColumnName="id")}, inverseJoinColumns={ @JoinColumn(name="student_id", referencedColumnName="id") )
    private Class class;
    

    Using JoinTable hase certain advantages with respect to caching and also lazy loading. For example OneToOne relationship if no instrumentation is used may have difficulties with LazyLoading depending on who is owning the relationship.

    Also using JoinTable for unidirectional relationships is the recommended by hibernate aproach. It is also more extensivle when you are not sure if one relationship would be OneToOne, OneToMany or ManyToMany when having join table you can esaily extend it.