Monday, March 12, 2012

JPA Hibernate one-to-many orphanRemoval

On a 1-n-relationship there is again the possibility for expression the relationship uni- or bidirectionally:
Unidirectional:
On the 1-side there is a collection, which is annotated with @OneToMany.
The collection consists of entities of the n-side.
Different parameters can be set:
- mappedBy
The owner of the relationship. Defined on the 1-side, than the n-side is owner of the relationship or the manager of this relationship. So here the instance variable of the n-site is stated.
Thus on the n-side a foreignKey field on default is maintained, in order for handling the relationship in the database.
- cascade
- fetch

If the relationship should be bidirectional, than also on the n-side an annotation by the instance variable must be set:
@ManyToOne
Here there are more interesting annotation / parameter which can be set.
But first of all the default
If there is no name stated with @JoinColumn, the foreignKey column has the following name:
name of the instance variable + _ + name of the primary key field

- @JoinColumn with the parameters:
  • referencedColumnName - Name of the foreignKey field
  • nullable - Must the relationship be set?
  • orphanRemoval - with true during deleting of the entity on the 1-side all referenced entities on the n-side will be deleted. This makes sense if a composition should be used. In some cases  @Embeddable respectively @Embedded could be an alternative. For the realisation of the composition, that means the parts of the composition will be managed by the head of the composition and the parts should never exists without the head or the composition, one should set on the mappedBy the 1-side as owner. Therefore during deletion of the entity on the 1-side the JPA-provider respectively Hibernate will also delete the n-side.
  • cascade - with cascade = CascadeType.PERSIST one can define that calling persist on an entity all other related entities on the n-side will also be made persistent.
  • fetch - in relation to performance / load behaviour one should think at least twice

No comments:

Post a Comment