OiO.lk Blog java Hibernate throws: Cannot delete or update a parent row although parent row set to null
java

Hibernate throws: Cannot delete or update a parent row although parent row set to null


I have two entities: AutomaticBid and Bid, so that:

@Entity
public class AutomaticBid {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ave_id", nullable = false)
    private Ave ave;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "orig_bid_id", nullable = false)
    private Bid orginalBid;
}

and

public class Bid {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ave_id", nullable = false)
    private Ave ave;

    @ManyToOne(fetch = FetchType.LAZY, targetEntity = AutomaticBid.class)
    @JoinColumn(name = "automatic_bid")
    private AutomaticBid automaticBid;

}

I want to delete all Bid and all AutomaticBid for a given Ave, and proceed as follows:

for (Bid currentBid: ave.getBids()) {
       currentBid.setAutomaticBid(null);
}
    
 String deleteAutomBidQueryStr = " delete from AutomaticBid ab where ab.ave.id =:aveId";
 Query deleteAutomBidQuery = this.em.createQuery(deleteAutomBidQueryStr);
 deleteAutomBidQuery.setParameter("aveId", ave.getId());
 int entriesDeletedAb = deleteAutomBidQuery.executeUpdate();

However, on the last row, the following exception is thrown:

Cannot delete or update a parent row: a foreign key constraint fails (`hometodeal`.`bid`, CONSTRAINT `FKddu37um70c1liaqbqjn4pjb2g` FOREIGN KEY (`automatic_bid`) REFERENCES `automatic_bid` (`id`))

Since I am setting

currentBid.setAutomaticBid(null);

for all Bids within an Ave, why I am getting this exception?



You need to sign in to view this answers

Exit mobile version