high-performance-java-persistence icon indicating copy to clipboard operation
high-performance-java-persistence copied to clipboard

Add tests for delete parent entity with @OneToMany cascade = ALL

Open ivan-zaitsev opened this issue 3 years ago • 1 comments

Hi, Vlad. I wrote some tests with delete operation after tricky select.


Test class - DeletingAfterFetchWithoutSQLCascadeTest

Test method - testDeleteParentAfterEagerInnerFetchInChildWithoutSQLCascadeInOneTransaction

When we try to delete parent entity (Audience) after select with join fetch with list of Lesson and inside them also join list of Group (groups also have lessons, and they have EAGER fetch mapping). The ConstraintViolationException will occur after parent (Audience) delete. Even if we try to delete child entities (Lesson) explicitly before parent delete (Audience), anyway the same exception will occur.

Test method - testDeleteParentAfterEagerInnerFetchInChildWithoutSQLCascadeThenSaveAnotherEntityInDifferentTransactions

In this test case we have the same logic, but do all operations in different transactions.


Test class - DeletingAfterFetchWithSQLCascadeTest

Test method - testDeleteParentAfterEagerInnerFetchInChildWithSQLCascadeInOneTransaction

In this test case we have similar logic, but the database lesson table doesn't have ON DELETE CASCADE constraint. And we have another exception - TransientPropertyValueException.

Test method - testDeleteParentAfterEagerInnerFetchInChildWithSQLCascadeThenSaveAnotherEntityInDifferentTransactions

In this test case we have the same logic, but if we do all operations in different transactions. And the TransientPropertyValueException will occur not after parent (Audience) delete, but in the next operation, for example - merge different Audience that doesn't belong to the main select with join fetch.


Possible solutions to resolve this problem: set fetch = FetchType.LAZY for lessons in Group OR @OnDelete(action = OnDeleteAction.CASCADE) instead of cascade = CascadeType.ALL OR entityManager.clear(); before delete Audience OR add sql cascades and @GeneratedValue(strategy = GenerationType.SEQUENCE)


Just for examination, spring data jpa issue: https://github.com/spring-projects/spring-data-jpa/issues/2281

ivan-zaitsev avatar Nov 09 '21 17:11 ivan-zaitsev

Thanks. I'll check it out when I have some time.

vladmihalcea avatar Nov 09 '21 18:11 vladmihalcea