I have two tables with OneToMany relation
class ServiceProvider {
...
@OneToMany(fetch=FetchType.EAGER,mappedBy="serviceProvider", cascade={CascadeType.ALL,CascadeType.REMOVE},orphanRemoval = true) @OnDelete(action=OnDeleteAction.CASCADE) private List serviceCenters; ...
}
class ServiceCenterDetails {
... //bi-directional many-to-one association to ServiceProviderDomainMap @ManyToOne @JoinColumn(name="SERVICE_PROVIDER_ID") private ServiceProvider serviceProvider;
...
}
I am trying to delete provide row. But i am getting below error:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (fixoline
.service_center_details
, CONSTRAINT FK_qvahoxeovx9vmwl6mcu2c0lyw
FOREIGN KEY (SERVICE_PROVIDER_ID
) REFERENCES service_provider
(ID
))
below is the way i am trying
String hql = "DELETE FROM ServiceProvider WHERE id = :providerId"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setParameter("providerId",providerId); int result = query.executeUpdate();
could someone pls help resolving it?
First, we'll start with CascadeType. REMOVE which is a way to delete a child entity or entities when the deletion of its parent happens. Then we'll take a look at the orphanRemoval attribute, which was introduced in JPA 2.0. This provides us with a way to delete orphaned entities from the database.
Then how do we delete the child entity from the database? Hibernate does that automatically when you set the orphanRemoval attribute of the @OneToMany annotation to true and the cascade attribute to CascadeType. ALL , it auto delete child entities while deleting parent.
There are two tings,
Why you are using @OnDelete
when you using CascadeType.ALL
in @oneToMany
? CascadeType.ALL
will delete child entities when parent is deleted.
@OnDelete
mainly used in child entities with @ManyToOne
not otherwise.
Try with any option and check.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With