Mappings
-
One-to-One
-
E.g., a instructor has its details in a separate table

- Use
@OneToOneand@JoinColumn(name = fk_field) -
Use
@OneToOne(mappedBy=instructorDetail)for a bidirectional (when the first unidirectional reference has already been made). This uses the instructorDetail property of Instructor class and use its information of @JoinColumn -
One-to-Many (Many-to-One)
-
E.g., a instructor can have multiple courses
- One-to-Many relationships can be unidirectional or bidirectional

-
Do not use cascade delete if the reference is bidirectional
-
Many-to-Many
-
E.g., a course can have many students, students can have many courses

- Never use cascade delete on many to many relationships
Cascade Types
Cascadeis the action of applying the same operation to related entities- Cascading finds the related table by the
primary keyandforeign key -
By default, no operations are cascaded
-
Cascade Types
Persist: if entity is saved, related entity will also be savedRemove: if entity is removed, related entity will also be removedRefresh: if entity is refreshed, related entity will also be refreshedDetach: if entity is detached, related entity will also be detachedMerge: if entity is merged, related entity will also be mergedAll: all of the above cascade types
@Entity
@Table(name="instructor")
public class Instructor {
@OneToOne(cascade = CascadeType.All) // cascade all operations to the relatedentities
//@OneToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE}) // list of cascade types
@JoinColumn(name = "instructor_detail_id") // primary key
private InstructorDetail instructorDetail;
}
Data fetch
- Eager: retrieve everything from all related tables in one shot
- Lazy: retrieve the data from the related tables only when requested (on demand). Preferred!
@OneToMany(mappedby = "instructor", fetch = FetchType.LAZY)- To retrieve data at a latter time, the hibernate session must be opened (otherwise it throws an exception - LazyInitializationException).
| Mapping | Default Fetch Type |
|---|---|
| @OneToOne | FetchType.EAGER |
| @OneToMany | FetchType.LAZY |
| @ManyToOne | FetchType.EAGER |
| @ManyToOne | FetchType.LAZY |
Join Table
Join Tableis a table that provides a mapping between 2 tables in aMany To Manyrelationship- It has a
foreign keyfor each of both tables. - The foreign keys are also the primary key of the join table
@JoinTableis used for Many to Many relationships

- Join Column

- Inverse Join Column Inverse
