2.5.2.12. Many To Many
When an entity A references multiple B entities, and other As might reference some of the same Bs, we say there is a many to many relation between A and B.
In our sample model, for example, each article has a reference to all the authors that contributed to the article.
Other articles might have some of the same authors.
We say, then, that Article and Author have a many to many relation through the Article.authors field.
JPA indicates many to many relations between entities with the ManyToMany annotation.
This annotation has the following properties:
-
Class targetEntity: The class of the related entity type. This information is usually taken from the parameterized collection or map element type. You must supply it explicitly, however, if your field isn’t a parameterized type. -
String mappedBy: Names the many to many field in the related entity that maps this bidirectional relation. We explain bidirectional relations in Bidirectional Relations above. Leaving this property unset signals that this is a standard unidirectional relation. -
CascadeType[] cascade: Array of enum values defining cascade behavior for the collection elements. We explore cascades above in Cascade Type. Defaults to an empty array. -
FetchType fetch: Whether to load the field eagerly (FetchType.EAGER) or lazily (FetchType.LAZY). Defaults toFetchType.LAZY. See Fetch Type above for details on fetch types.
The equivalent XML element is many-to-many.
It accepts the following attributes:
-
name: The name of the field or property. This attribute is required. -
target-entity: The class of the related type. -
fetch: One ofEAGERorLAZY. -
mapped-by: The field that owns the relation. See Field and Property Metadata.
You may also nest the cascade element within a
many-to-many element.