Issue
I have issues with some two entities, that have relation to same entity.
So, I have Transaction (do not confuse it with session transaction), TransactionItem, Customer and Subscription. Both, Transaction and Customer has relation Subscription.
Transaction.java
@OneToMany(
mappedBy = "transaction",
cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
orphanRemoval = true
)
private List<TransactionItem> transactionItems;
TransactionItem.java
@OneToOne(mappedBy = "transactionItem", cascade = CascadeType.ALL,
fetch = FetchType.LAZY)
private Subscription subscription;
Customer.java
@OneToMany(
mappedBy = "customer",
cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
orphanRemoval = true
)
private List<Subscription> subscriptions;
Subscription.java
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id", referencedColumnName = "guid")
private Customer customer;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "transaction_id", referencedColumnName = "guid")
private TransactionItem transactionItem;
I add TransactionItem to Transaction and then Subscription to TransactionItem. Nothin special really.
When Transaction is being saved hibernate save all dependant relations as well, which is fine and expected.
The issue is when I try to refresh Customer, that have one more Subscription attached, I get old entity. I tried to flush, evict, clear ... but nothing seems to work. I tried to search for the solution but I found nothing, that could help me out with it.
I am working with spring boot 2.1.1
Thanks for help!
Solution
What I had to do was to clear the persistence context of EntityManager. Usually with using jpa you do not want to do this manualy but in this case I had no other choice.
//aquire instance of EntityManager in your bean
@Autowired
private EntityManager entityManager;
//then when everything is saved we need to flush the changes and then clear context
entityManager.flush();
/**
*
* From the javax.persistence.EntityManager documentation:
*
* Clear the persistence context, causing all managed
* entities to become detached. Changes made to entities that
* have not been flushed to the database will not be
* persisted.
*/
entityManager.clear();
Answered By - Matjaz
Answer Checked By - Clifford M. (JavaFixing Volunteer)