Search code examples
javahibernatehibernate-mapping

Hibernate relational annotations


Suppose i have student and want to map each student with a house .

Say Entity 1 : Student_master table is described as (Student_id(primary_key),Standard,grade,age)

Say Entity 2 : house_master table is described as (house_id(primary_key),house_color_house_capacity)

Say Entity 3 :student_house_mapping table is (student_house_id,Student_id(foreign_key),house_id(foreign_key)).

Now here I have to traverse through each student and get its house details ,

For Example , i get a student , now through student_house_mapping table i get the house_id and with it i get a specific house_master object.

How in hibernate could this be achieved using relational (Example : one to one, many to one)annotations , if I have the classes for all the entities


Solution

  • By reading the first sentence, I can say that It is OneToOne as you stated that Each Student has A House.

    If you consider a scenario, Each student can have many houses. Then, the relationship would be OneToMany and achieved by only two tables students and houses with Student having OneToMany with House(POJO classes).

    If you think that even the house can belong to many students. Then, you should go for ManyToMany with your present tables students, houses and students_house table(Bridge table).

    Student.java

    @Entity
    @Table(name="students")
    public class Student {
    private int studentId;// set the column name with @JoinColumn  annotation if you want
    private int standard;// to be different from the variable name
    private int grade;
    private int age;
    @OneToMany
    @JoinTable(name="students_houses",
        joinColumns = @JoinColumn(name="studentId"),
        inverseJoinColumns = @JoinColumn(name="houseId"))
    private List<House> houses;
    // getters and setters
    }
    

    House.java

    @Entity
    @Table(name="houses")
    public class House {
    private int houseId;
    private String color;
    private int houseCapacity;
    @OneToMany
    @JoinTable(name="students_houses",
        joinColumns = @JoinColumn(name="houseId"),
        inverseJoinColumns = @JoinColumn(name="studentId"))
    private List<Student> students;
    // getters and setters
    }
    

    If you want to create custom Bridge table with additional fields other than foreign keys of both the tables, You can create a custom Bridge class with Each class having OneToMany with the Bridge class. And Bridge class having ManyToOne with the both classes.

    You can refer the stackoverflow documentation for further examples