Entity Relationship Overview
Restaurant Entity
- Extends:
BaseEntity
- Attributes:
private String name;
private String address;
private String city;
private String description;
- Association:
@OneToMany(mappedBy = "myRestaurant", cascade = CascadeType.ALL)
private List<FoodItem> foodItems = new ArrayList<>();
(Initialized to avoid NullPointerException)
- Role: Parent, non-owning (inverse) side of the bidirectional association.
- Project Tip: Exclude
foodItems
from toString()
to prevent infinite recursion (stack overflow).
FoodItem Entity
- Attributes:
private String itemName;
private String itemDescription;
private boolean isVeg;
private int price;
- Association:
@ManyToOne
@JoinColumn(name = "restaurant_id")
private Restaurant myRestaurant;
- Role: Child, owning side of the bidirectional association (contains the foreign key).
- Note: In a one-to-many bidirectional relationship, the many side (
FoodItem
) is always the owning side to maintain normalization.
JPA Annotations for Associations
@OneToMany
@ManyToOne
@OneToOne
@ManyToMany
Problem with Bidirectional Association
- Issue: Hibernate creates an unnecessary join table (e.g.,
restaurants_food_items
) because it cannot automatically determine the owning and inverse sides in a bidirectional association.
- Cause: Lack of explicit ownership definition in the
@OneToMany
annotation.
- Solution: Use the
mappedBy
attribute in the @OneToMany
annotation on the inverse side (Restaurant
).
- Syntax:
@OneToMany(mappedBy = "myRestaurant")
- Explanation:
mappedBy
specifies the property name (myRestaurant
) on the owning side (FoodItem
) that manages the foreign key.
Customizing Foreign Key