Cascade Type

Cascade Type

http://openjpa.apache.org/builds/2.4.0/apache-openjpa/docs/jpa_overview_meta_field.html#jpa_overview_meta_cascade

2.9.  Many To One

When an entity A references a single entity B, and other As might also reference the same B, we say there is a many to one relation from A to B. In our sample model, for example, each magazine has a reference to its publisher. Multiple magazines might have the same publisher. We say, then, that the Magazine.publisher field is a many to one relation from magazines to publishers.

JPA indicates many to one relations between entities with the ManyToOne annotation. This annotation has the following properties:

  • Class targetEntity: The class of the related entity type.
  • CascadeType[] cascade: Array of enum values defining cascade behavior for this field. We explore cascades below. Defaults to an empty array.
  • FetchType fetch: Whether to load the field eagerly (FetchType.EAGER) or lazily (FetchType.LAZY). Defaults to FetchType.EAGER. See Section 2.7.1, “ Fetch Type ” above for details on fetch types.
  • boolean optional: Whether the related object must exist. If false, this field cannot be null. Defaults to true.

The equivalent XML element is many-to-one. 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 of EAGER or LAZY.
  • optional: Boolean indicating whether the field value may be null.

We introduce the JPA EntityManager in Chapter 8, EntityManager .

The EntityManager has APIs to persist new entities, remove (delete) existing entities, refresh entity state from the datastore, and merge detached entity state back into the persistence context. We explore all of these APIs in detail later in the overview.

When the EntityManager is performing the above operations, you can instruct it to automatically cascade the operation to the entities held in a persistent field with the cascadeproperty of your metadata annotation. This process is recursive. The cascade property accepts an array of CascadeType enum values.

  • CascadeType.PERSIST: When persisting an entity, also persist the entities held in this field. We suggest liberal application of this cascade rule, because if the EntityManagerfinds a field that references a new entity during flush, and the field does not use CascadeType.PERSIST, it is an error.
  • CascadeType.REMOVE: When deleting an entity, also delete the entities held in this field.
  • CascadeType.REFRESH: When refreshing an entity, also refresh the entities held in this field.
  • CascadeType.MERGE: When merging entity state, also merge the entities held in this field.

Note

OpenJPA offers enhancements to JPA’s CascadeType.REMOVE functionality, including additional annotations to control how and when dependent fields will be removed. See Section 4.2.1, “ Dependent ” for more details.

CascadeType defines one additional value, CascadeType.ALL, that acts as a shortcut for all of the values above. The following annotations are equivalent:

@ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REMOVE,
    CascadeType.REFRESH,CascadeType.MERGE})
private Company publisher;
@ManyToOne(cascade=CascadeType.ALL)
private Company publisher;

In XML, these enumeration constants are available as child elements of the cascade element. The cascade element is itself a child of many-to-one. The following examples are equivalent:

<many-to-one name="publisher">
    <cascade>
        <cascade-persist/>
        <cascade-merge/>
        <cascade-remove/>
        <cascade-refresh/>
    </cascade>
</many-to-one>
<many-to-one name="publisher">
    <cascade>
        <cascade-all/>
    </cascade>
</many-to-one>

2.10.  One To Many

When an entity A references multiple B entities, and no two As reference the same B, we say there is a one to many relation from A to B.

One to many relations are the exact inverse of the many to one relations we detailed in the preceding section. In that section, we said that the Magazine.publisher field is a many to one relation from magazines to publishers. Now, we see that the Company.mags field is the inverse – a one to many relation from publishers to magazines. Each company may publish multiple magazines, but each magazine can have only one publisher.

JPA indicates one to many relations between entities with the OneToMany 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 one field in the related entity that maps this bidirectional relation. We explain bidirectional relations below. 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 Section 2.9.1, “ Cascade Type ”. Defaults to an empty array.
  • FetchType fetch: Whether to load the field eagerly (FetchType.EAGER) or lazily (FetchType.LAZY). Defaults to FetchType.LAZY. See Section 2.7.1, “ Fetch Type ” above for details on fetch types.

The equivalent XML element is one-to-many, which includes 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 of EAGER or LAZY.
  • mapped-by: The name of the field or property that owns the relation. See Section 2, “ Field and Property Metadata ”.

You may also nest the cascade element within a one-to-many element.

2.10.1.  Bidirectional Relations

When two fields are logical inverses of each other, they form a bidirectional relation. Our model contains two bidirectional relations: Magazine.publisher and Company.mags form one bidirectional relation, and Article.authors and Author.articles form the other. In both cases, there is a clear link between the two fields that form the relationship. A magazine refers to its publisher while the publisher refers to all its published magazines. An article refers to its authors while each author refers to her written articles.

When the two fields of a bidirectional relation share the same datastore mapping, JPA formalizes the connection with the mappedBy property. Marking Company.mags as mappedByMagazine.publisher means two things:

  1. Company.mags uses the datastore mapping for Magazine.publisher, but inverses it. In fact, it is illegal to specify any additional mapping information when you use the mappedBy property. All mapping information is read from the referenced field. We explore mapping in depth in Chapter 13, Mapping Metadata .
  2. Magazine.publisher is the „owner“ of the relation. The field that specifies the mapping data is always the owner. This means that changes to the Magazine.publisher field are reflected in the datastore, while changes to the Company.mags field alone are not. Changes to Company.mags may still affect the JPA implementation’s cache, however. Thus, it is very important that you keep your object model consistent by properly maintaining both sides of your bidirectional relations at all times.

You should always take advantage of the mappedBy property rather than mapping each field of a bidirectional relation independently. Failing to do so may result in the JPA implementation trying to update the database with conflicting data. Be careful to only mark one side of the relation as mappedBy, however. One side has to actually do the mapping!

Note

You can configure OpenJPA to automatically synchronize both sides of a bidirectional relation, or to perform various actions when it detects inconsistent relations. See Section 5, “ Managed Inverses ” in the Reference Guide for details.

2.11.  One To One

When an entity A references a single entity B, and no other As can reference the same B, we say there is a one to one relation between A and B. In our sample model, Magazinehas a one to one relation to Article through the Magazine.coverArticle field. No two magazines can have the same cover article.

JPA indicates one to one relations between entities with the OneToOne annotation. This annotation has the following properties:

  • Class targetEntity: The class of the related entity type. This information is usually taken from the field type.
  • String mappedBy: Names the field in the related entity that maps this bidirectional relation. We explain bidirectional relations in Section 2.10.1, “ 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 this field. We explore cascades in Section 2.9.1, “ Cascade Type ” above. Defaults to an empty array.
  • FetchType fetch: Whether to load the field eagerly (FetchType.EAGER) or lazily (FetchType.LAZY). Defaults to FetchType.EAGER. See Section 2.7.1, “ Fetch Type ” above for details on fetch types.
  • boolean optional: Whether the related object must exist. If false, this field cannot be null. Defaults to true.

The equivalent XML element is one-to-one which understands 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 of EAGER or LAZY.
  • mapped-by: The field that owns the relation. See Section 2, “ Field and Property Metadata ”.

You may also nest the cascade element within a one-to-one element.

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 Section 2.10.1, “ 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 Section 2.9.1, “ Cascade Type ”. Defaults to an empty array.
  • FetchType fetch: Whether to load the field eagerly (FetchType.EAGER) or lazily (FetchType.LAZY). Defaults to FetchType.LAZY. See Section 2.7.1, “ 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 of EAGER or LAZY.
  • mapped-by: The field that owns the relation. See Section 2, “ Field and Property Metadata ”.

You may also nest the cascade element within a many-to-many element.

2.13.  Order By

Datastores such as relational databases do not preserve the order of records. Your persistent List fields might be ordered one way the first time you retrieve an object from the datastore, and a completely different way the next. To ensure consistent ordering of collection fields, you must use the OrderBy annotation. The OrderBy annotation’s value is a string defining the order of the collection elements. An empty value means to sort on the identity value(s) of the elements in ascending order. Any other value must be of the form:

<field name>[ ASC|DESC][, ...]

Each <field name> is the name of a persistent field in the collection’s element type. You can optionally follow each field by the keyword ASC for ascending order, or DESC for descending order. If the direction is omitted, it defaults to ascending.

The equivalent XML element is order-by which can be listed as a sub-element of the one-to-many or many-to-many elements. The text within this element is parsed as the order by string.

Comments

comments

Close Menu
Show Buttons
Hide Buttons