In this example, you will learn how to map many-to-one relationship using Hibernate Annotations. Consider the following relationship between Student and Address entity.
According to the relationship many students can have the same address.
To create this relationship you need to have a STUDENT and ADDRESS table. The relational model is shown below.
To create the STUDENT and ADDRESS table you need to create the following Java classes with hibernate annotations.
Student class is used to create the STUDENT table.
The @ManyToOne annotation is used to create the many-to-one relationship between the Student and Address entities. The cascade option is used to cascade the required operations to the associated entity. If the cascade option is set to CascadeType.ALL then all the operations will be cascaded. For instance when you save a Student object, the associated Address object will also be saved automatically.
Address class is used to create the ADDRESS table.
Now create the hibernate configuration file with the Student and Address class mapping.
Create the Main class to run the example.
On executing the Main class you will see the following output.
The Student table has two records.
The Address table has one record.
Both the student records points to the same address record, this illustrates the many-to-one mapping.
No comments:
Post a Comment