Object-relational mapping

One entity may have an attribute which references the other entity. This defines a directionality. In JPA, relationships are only unidirectional, meaning that only one entity can reference the other.

Based on the directionality, one entity’s role is “source” while the other is “target”.

In one-to-one and one-to-many cardinalities, foreign keys are used to implement the relationship. The ownership of the relation is kept by the entity having the foreign key as attribute.

A reference can be single-valued or set-valued (if it has a collection of references). Therefore, there are four possible types of cardinality: one-to-one, one-to-many, many-to-one, many-to-many.

1:N relationships can be achieved in two ways, either by using the JoinColumn annotation or with the mappedBy parameter. In the first case, JPA uses a bridge table (as for N:M relationships). Otherwise, JPA is instructed to not create a bridge table, as the relationship is already being mapped by a FK in the opposite entity.

Entity manager

Entity lifecycle

image.png

Signature Description
public ****void persist(Object entity) Makes an entity instance become part of the persistence context, i.e., managed
public <T> T find(Class<T> entityClass, Object primaryKey) Finds an entity instance by its primary key
public ****void remove(Object entity) Removes an entity instance from the
persistence context and thus from the
database
public ****void refresh(Object entity) Resets the state of entity instance from the
content of the database
public ****void flush() Writes the state of entities to the database
as immediately as possible