Search code examples
javajpaentityentity-relationshipcascade

JPA cascades creating tight couplings


JPA provides cascades which can be used to automatically persist/update/remove other entities a particular entity depends on. Let's say I have three entities: Job, BankAccount and Person (which has a OneToMany relationship with the first two entities). In the absence of cascade events, I would write:

person.addJob(job);
person.addBankAccount(bankAccount);

em.persist(job);
em.persist(bankAccount);
em.persist(person);

Cascaded events (with the type of CascadeType.PERSIST for instance) make me able to omit first two persist() calls and ensure that a single em.persist(person); call will also persist dependent entities.

Now, this makes the code which acts on entities tightly coupled with their internals. The way I manage entities is now tightly bound to the annotations I used inside the entities. Can this be considered as a bad practice because of the additional coupling it introduces?


Solution

  • Not really, it's fairly standard practice to leverage cascading operations.

    You should create integration tests that verify any cascades annotated on your domain actually occur.