Question

How do you implement aggregation and decomposition with Java Persistence API? What are the best practices?

Thanks in advance, Daniel

Was it helpful?

Solution

I've found the orphanRemoval attribute for @OneToMany and @OneToOne relationships:

When a target entity in one-to-one or one-to-many relationship is removed from the relationship, it is often desirable to cascade the remove operation to the target entity. Such target entities are considered “orphans,” and the orphanRemoval attribute can be used to specify that orphaned entities should be removed. For example, if an order has many line items, and one of the line items is removed from the order, the removed line item is considered an orphan. If orphanRemoval is set to true, the line item entity will be deleted when the line item is removed from the order.

Usage:

@OneToMany(mappedBy="customer", orphanRemoval=true)
public List<Order> orders;

OTHER TIPS

There are two things which should be very clear while handling aggregation in JPA.

  1. The relationship in the relational world.
  2. The relationship required in the object world.

The relationship in Java world is governed by the domain need. For example a User might have many addresses so we keep the make the aggregation of address in User and not keep the inverse relationship. For composition, we need to handle the cascade behavior.

A more detail treatment can be see here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top