Hibernate delete from onetomany

被刻印的时光 ゝ 提交于 2021-01-27 05:23:29

问题


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?


回答1:


The error message is quite clear: There are foreign key references to the ServiceProviders you are trying to delete. Delete ServiceCenterDetails first:

delete from ServiceCenterDetails where serviceProvider.id = :providerId



回答2:


There are two tings,

  1. Why you are using @OnDelete when you using CascadeType.ALL in @oneToMany? CascadeType.ALL will delete child entities when parent is deleted.

  2. @OnDelete mainly used in child entities with @ManyToOne not otherwise.

Try with any option and check.




回答3:


Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails

this exception tells that you should delete your ServiceCenterDetails associated with ServiceProviders first and then delete the ServiceProviders.



来源:https://stackoverflow.com/questions/34831438/hibernate-delete-from-onetomany

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!