Relationships among entities may be one-to-one, one-to-many, many-to-one, or many-to-many. Relationships are polymorphic.
If there is an association between two entities, one of the following relationship modeling annotations MUST be applied to the corresponding persistent property or instance variable of the referencing entity: OneToOne, OneToMany, ManyToOne, ManyToMany. For associations that do not specify the target type (e.g., where Java generic types are not used for collections), it is necessary to specify the entity that is the target of the relationship.
Relationships may be bidirectional or unidirectional. A bidirectional relationship has BOTH an owning side and an inverse side. A unidirectional relationship has ONLY an owning side. The owning side of a relationship DETERMINES the updates to the relationship in the database.
The following rules apply to bidirectional relationships:
The inverse side of a bidirectional relationship MUST refer to its owning side by use of the mappedBy element of the OneToOne, OneToMany, or ManyToMany annotation. The mappedBy element DESIGNATES the property or field in the entity that is the owner of the relationship.
The many side of one-to-many / many-to-one bidirectional relationships MUST be the owning side, hence the mappedBy element CANNOT be specified on the ManyToOne annotation.
For one-to-one bidirectional relationships, the owning side corresponds to the side that contains the corresponding foreign key.
For many-to-many bidirectional relationships either side may be the owning side.
The relationship modeling annotation constrains the use of the cascade=REMOVE specification. The cascade=REMOVE specification should ONLY be applied to associations that are specified as OneToOne or OneToMany. Applications that apply cascade=REMOVE to other associations are not portable.
Note that it is the application that bears responsibility for maintaining the consistency of runtime relationships - for example, for insuring that the "one" and the "many" sides of a bidirectional relationship are consistent with one another when the application updates the relationship at runtime.
If there are no associated entities for a multi-valued relationship of an entity fetched from the database, the persistence provider is responsible for returning an EMPTY COLLECTION as the value of the relationship.