I have some tables managed by Hibernate with various foreign key constraints. Cascade on delete is currently managed by Hibernate alone. For playing around with test data I
I see two potential issues:
Probably there are some other situations that could be problematic in some scenarios, so I would recommend not to do it.
Don't use cascade = CascadeType.REMOVE Documentation here
Because of your db may be destroyed. You can use formal order. Delete sub stable and then remove master table
You can use the native database functionality to delete the child records upon deletion of parent record.
Be aware of bi-directional relationships and to be sure, ensure you just specify insert and update in cascade (to be on safer side).
You mention for testing purposes. I'm guessing, execute some test, delete data, replay test...
When using second-level caching or query cache, the cache will and up being stale if you directly remove the data from the database. This might result in unexpected test results.
So yes, this will conflict with Hibernate if you use second-level / query caching as the entity's will not get evicted from cache. Make sure all caches get cleared after you directly deleted any data. See this question on how to clear cache.
The official Hibernate docs also mention this:
Be aware that caches are not aware of changes made to the persistent store by other applications. They can, however, be configured to regularly expire cached data.
You can use CascadeType.DELETE, however this annotation only applies to the objects in the EntityManager, not the database. You want to be sure that ON DELETE CASCADE is added to the database constraint. To verify, you can configure JPA to generate a ddl file. Take a look at the ddl file, you'll notice that ON DELETE CASCADE is not part of the constraint. Add ON DELETE CASCADE to actual SQL in the ddl file, then update your database schema from the ddl. This will fix your problem .
This link shows how to use ON DELETE CASCADE on for CONSTRAINT in MySQL. You do this on the constraint. You can also do it in a CREATE TABLE or ALTER TABLE statement. It's likely that JPA creates the constraint in an ALTER TABLE statement. Simply add ON DELETE CASCADE to that statement.
Note that some JPA implementors do provide a means for this functionality.
Hibernate does supply this functionality using the @OnDelete annotation, thus it is preferred to use this or simply update the ddl file if you would like to stick with standard JPA functionality.
You can safely use ON DELETE CASCADE as long as you do not have CascadeType.REMOVE or orphanRemoval enabled to prevent propagation of the entity removal event.
Having @OnDelete(action = OnDeleteAction.CASCADE) on your relation will force Hibernate to generate ON DELETE CASCADE for related foreign keys. However your Dialect has to indicate that such relation are supported by returning true in supportsCascadeDelete method.
Dialect.supportsCascadeDelete()
OnDelete