Monday, March 12, 2012

binary assoziation JPA


one-to-one-relationship with JPA

For this there is the JPA annotation @OneToOne.
Per default this is done by foreignKey in the database.

Unidirectional

In a unidirectional @OneToOne-relationship the entity from which one can navigate to the other entity gets the @OneToOne-annotation.

mappedBy

if the one-to-one relationship of the two entities should be bidirectionally,
on every entity the @OneToOne-annotation must be set and with help of the mappedBy-attribute it is defined which side manages the relationship.
The relationship with the entity, which has the mappedBy, will be be managed by the other side and the parameter will be set to the referred property.
The result is that is defined on which side the foreignKey-column will be applied  to.
The entity without the mappedBy-attribute gets in the according table the foreignKey-column, so that the relationship can be expressed. The name is derived from:
Table name of the referred table + _ + column name of the primary key.


@Entity
public class A {
 @OneToOne
 B b;
 ...
}

@Entity
public class B {

@OneToOne(mappedBy="b")
A a;

Persist @OneToOne per JPA

During persist of an @OneToOne-relationship one must set the relation pragmatically and both entities / every side must be made persistent by means of calling the persist-method.


cascade=CascadeType.PERSIST

To avoid, that both entities of an @OneToOne-relationship must be saved separately,
one can take advantage of the cascade-attribute of the @OneToOne-relationship:
@OneToOne(cascade=CascadeType.PERSIST).
As a result the relationship of an entity will also be made persistent.
An OneToOne-relationship owns the entity without the mappedBy-attribute 
and has the foreignKey-column , so that the entity and the connected other entity will be made persistent.
So no need for calling persist() twice, calling persist on entity A is enough, B will also be made persistent.

optional

There is a parameter optional in context of an @OneToOne-relationship, which decides if the relationship must be set or not.

@OneToOne(optional=true)

No comments:

Post a Comment