Sunday, August 21, 2016

HIBERNATE: ONE TO MANY MAPPING

This kind of relationship is denoted through @OneToMany annotation. An optional annotation, @JoinTable can be used to rename the join-table and the constituent attributes.





This is how the vehicle class looks like when the relationship is one-way!!





Finally, in the main method, first the individual Vehicle objects are defined and then each of them gets assigned to the inner arraylist of the parent entity.





This is how the schema looks like. @JoinTable attributes' influence can be seen here clearly with the names.
Basically, two separate tables are created for the both entities and a table is created just for the sake of joining both the entities.






If a two-way relationship is required, in that case, a UserDetails object must be contained within the Vehicle class too. This way, one can fetch the owner of a vehicle. 
This is done using @ManyToOne annotation after the object aforementioned has been placed.






With the changed structure of the Vehicle entity, now one must also save the user for each vehicle to retain the two-way relationship.





The schema remains the same!


However, the above schema is redundant as the extra table is unnecessary. The extra table can be merged into the schema of the vehicle. This can be done by removing the settings previously made and setting the 'mappedBy' attribute of @OneToMany annotation. mappedBy takes the name of the member variable that provides the connection from the other class.







This is the class that provides the join this time, therefore containing the USER_ID foreign key. @JoinTable annotation can be used to rename the table though.




This is the resultant schema, thereby reducing the redundant join table.





No comments:

Post a Comment