Search code examples
javahibernateeclipselinkpersistencejpa-2.1

What is the significance of being the realtionship owner and how does CASCADE work with the two sides in JPA?


I have two tables. Transactions and Errors. There exists a One-To-Many relationship between Transactions and Errors. This is a bi-directional relationship and Errors is the owning side as @JoinColumn is specified in the Errors class. I want to understand what exactly does it mean to "OWN" the relationship. Say at the moment I have,

  • PROCESSED (column in TRANSACTIONS) set to N
  • ACTIVE (column in ERRORS) set to 1

Scenario 1: Now lets suppose we execute the below code.

transactions.setProcessed("Y");
errors.setActive(0);
transactions.setErrors(errors);
entityManager.merge(transactions);

I understand that the PROCESSED field will get set to "Y" in TRANSACTIONS but will the ACTIVE field in ERRORS also get set to 0 or not given that transactions IS NOT the OWNING side of the relationship?

Scenario 2: On the other hand, if we execute the below:

errors.setActive(0);
transactions.setProcessed("Y");
errors.setTransactions(transactions);
entityManager.merge(errors);

I understand that the ACTIVE filed in ERRORS will be set to 0 but will the PROCESSED field in TRANSACTIONS also be set to "Y" given that ERRORS IS the OWNING side of the relationship?

How do JPA cascade types tie into scenarios like this?


Solution

  • When we say that Errors is the owning side, that means foreign key of the relationship lies within the Errors table(which you are doing via @JoinColumn). Thus, the owning side of the relationship is the one in which reference column of the other entity will be present. You can define the inverse side of relationship by specifying @OneToMany in the Transactions entity.

    Now comes the second part of your question regarding the update of transactions and errors. In my view you can update List associated with a transaction by applying appropriate mode of cascade(persist,delete etc) which means you can specify in your Transaction entity @OneToMany(cascade=CASCADETYPE.MERGE) while specifying the inverse relationship. In this way, if whenever you will update a transaction row, corresponding error rows can also be updated.

    However, I don't think it is a good practice to cascade in the other way ie if you update child entity the parent entity should also get updated as it may lead to many data inconsistencies