C. one-to-many Relationship
A one-to-many relationship defines a reference to a collection of objects. Since a use case typically requires traversal from a parent object to a child object, and may or may not need to traverse from a child object to a parent object, a one-to-many relationship is the most common type of relationship in the object model; This means that a one-way one-to-many relationship can satisfy most situations.
That is, if a use case requires traversal from a child object to a parent object, you can easily add a many-to-many relationship in a subclass to make it a two-way relationship.
An entity that declares a one-to-many relationship is a parent object (and is not an owner). The table for this entity defines a primary key, but it does not have a foreign key (the foreign key is in a child object).
The object referenced by this one-to-many relationship is the child object and the owner of the relationship. Child objects have foreign keys and reference the parent object's primary key.
In Hibernate, the mapping of a one-to-many relationship is usually done by adding the column to the child table of the foreign key, but the details of the mapping are different depending on whether it is a one-way one-to-many relationship or a two-way one-to-many relationship.
In a one-way relationship, a foreign key column in a child table does not map to a property in a child object, it is in the data model, not in the object model. Because it is one-way, there are attributes only in the parent object, but not in child objects. In addition, the foreign key column must be defined as nullable, because Hibernate will first insert the Zikong (using a NULL foreign key) and update it later.
In a two-way relationship, object-relational mapping is better because there is a property in the child object for the foreign key column, and the column does not have to be empty in the database. However, the resulting object model has cyclic dependencies and a tighter coupling relationship between objects, and requires other programming to set the ends of the relationship.
As you can see, there are several trade-offs to consider about the definition of a one-to-many relationship, but it is often recommended that you use a one-way relationship unless the use case indicates that you need to navigate in two directions.
Object model
Mapping 13. One-to-many Relationship (POJO)
// Address (parent) entity
public class Address implements Serializable {
private Long addressId;
private Set phones = new HashSet();
...
}
// Phone (child) entity
public class Phone implements Serializable {
...
}
Hibernate Convention
In Hibernate, a one-to-many (one-way) relationship is mapped in the following ways:
In the parent class, use the settings, packages, or lists with a one-to-many child element.
If the relationship is one-way, create a foreign key in the table that represents the subclass, otherwise, use a many-to-many relationship for bidirectional relationships.