Advance Hibernate Mapping Overview

Basic Mapping:

Basic Mapping 
Java Class 
- frstName : String 
- lastName String 
- email String 
Hibernate 
Database Table 
o srst_nan. VARCHAR4S) 
o eme vARCHAR(4S)

Advance Mappings

  • In the database you most likely will have
    • Multiple tables
    • Relationships between Tables
  • Need to model this with Hibernate

Advanced Mappings Type

  1. One-to-One
  2. One-to-Many, Many-to-One
  3. Many-to-Many
One-to-One Mapping 
An instructor can have an "instructor detail" entity 
• Similar to an "instructor profile" 
Instructor 
Instructor 
Detail 
VASCHAR145)
One-to-Many Mapping 
An instructor can have many courses 
Course 
Course 
Instructor 
Course 
Course
Man> -to-Many Mapping 
A course can have many students 
A student can have many courses 
Course 
Course 
Course 
Course 
Student 
Student 
Student 
Student

Important Database Concepts

  • Primary key and foreign key
  • Cascade

Primary Key and Foreign Key

  • Primary Key: identify a unique row in a table
  • Foreign Key:
    • Link tables together
    • A field in one table that refers to primary key in another table
Foreign Key Example 
Table: instructor 
id 
1 
2 
first name 
Chad 
Madhu 
last name 
Darby 
Patel 
id 
100 
200 
Foreign key 
column 
instructor detail id 
100 
200 
Table: instructor detail 
youtube_channel 
www.luv2code.com/youtube 
www.youtube.com 
hobby 
Luv 2 Code!!! 
Guitar

Cascade

  • You can cascade operations
  • Apply the same operation to related entities
  • Whenever an object will be saved in the table “instructor”  then simultaneously the object will also be saved within another table “instruction_details”.
  • If we delete an instructor, we should also delete their instructor_detail.
    • This is known as ” CASCADE DELETE
Instructor 
Instructor 
Detail

Note: We should not perform cascade deletion operation in Many-to-Many mapping.

Fetch Types: Eager vs Lazy Loading

  • When we fetch / retrieve data, should we retrieve EVERYTHING?
    • Eager will retrieve everything in a single shot
    • Lazy will retrieve on request

Uni-Directional Relationship

  • Is a one way relationship
  • You have an “instructor” and then you have “instructor_detail”, so you will start with instructor object you load the instructor and then from there access the instructor detail.

Bi-Directional Relationship

  • Instructor and then they have its relation with instructor detail, but then also we can go the other way. So we can load the instructor details and have a reference to the instructor.
Instructor 
Instructor 
Detail

Leave a comment