Primary key is used to uniquely identify a row in a table.
Primary key can be used to link two tables together. When a primary key of one table is used in another table, it is known as a foreign key.
When one row in table_a corresponds to one row in table_b, then it is called a one-to-one relationship.
When one row in table_a corresponds to many rows in table_b, then it is called a one-to-many relationship.
The inverse of a one-to-many relationship is a many-to-one relationship where many rows in table_b correspond to one row in table_a.
When one row in table_a corresponds to many rows in table_b and one row in table_b corresponds to many rows in table_a, then we have what is called a many-to-many relationship.
When two tables are related to one another, data should reflect a consistent state. All foreign keys should refer to valid, existing primary key values.
Absence of referential integrity can lead to records being lost in the database.
Cascading means propagating an operation from the owning entity to the related entity. When a record in the owning entity (parent table) is saved, updated or deleted, the change should be reflected in the related entity (child table) as well.
JPA Cascade types:
Type | Meaning |
---|---|
Persist | Owning entity saved => related entity saved |
Merge | Owning entity merged => related entity merged |
Refresh | Owning entity refreshed => related entity refreshed |
Remove | Owning entity removed => related entity removed |
Detach | Owning entity manually detached => related entity detached |
All | All cascade operations on owning entity applied to related entity |
There are two ways in which data is loaded: eager and lazy.
- Eager fetch means that when a record is fetched from the database, all the associated records from related tables are also fetched. Eager fetch is the default fetch type used by Hibernate, but it is not always the most efficient.
- Lazy fetch fetches the records only when they are needed.
When we remove the relationship between a parent and child, the child record becomes an orphan record meaning that it does not have a parent record.
Orphan records mean that the database is in an inconsistent state.