Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate delete from onetomany

Tags:

java

hibernate

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?

like image 720
Gnani Avatar asked Jan 16 '16 19:01

Gnani


People also ask

How do I delete a JPA child record?

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.

How do you delete child records when parent is deleted in Hibernate?

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.


1 Answers

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.

like image 122
Kishor Avatar answered Sep 19 '22 22:09

Kishor