Clomez
Clomez

Reputation: 1512

Hibernate delete just won't fire

I've ask'd this before but still have no clue what is going on...

I've read about entity needing to be cleared of relationships before deleting, and about cascade.all in parent entity, however i still dont get how is hibernate not doing anything...

@Transactional
public void deleteAllinRange(LocalDate a, LocalDate b) {
List<Invoice> z = invoiceRepo.selector(a,b);
    for(Invoice x : z){
        x.setOwner(null);
        invoiceRepo.delete(x);
    }

going into for loop z list size is 314, and there is all the entities i expect there to be. I then tried to setOwner to null, since that is the only relationship to parent element.

After nulling owner, all the attributes in x entity are type long, string or localDate so surely there cant be any relationships to parent element?

Parent element is set of Invoices with List of invoice elements

@OneToMany(cascade=CascadeType.ALL, mappedBy = "owner", orphanRemoval = true)
@JsonManagedReference
private List<Invoice> invoices = new ArrayList<>();

java fill just run invoiceRepo.delete(x); x 314, but will actually do nothing at all and SQL debugging shows there is not even attempt to remove anything, noting is queried here...

Why is this happening? Why is there not any queries, no errors, no nothing.

Upvotes: 0

Views: 609

Answers (1)

Bahadir Tasdemir
Bahadir Tasdemir

Reputation: 10783

When you setOwner and don't save the x, then it has no effect. Also, if you have a constraint nullable=false, you cannot set it to null.

What do you want to do? Do you want to delete Invoices and remain the owners? Then you should remove the orphanRemoval = true.

Or else, if you want to remove the orphans, leave it as is and just delete the Invoices without setting the owner null. It will remove orphaned owners automatically.

If you want to manage them manually, don't set a foreign key and break the relation between them, just delete any record when you want and set fields yourself null or value.

In addition, you can also use the method delete(Iterable iterable) of the repository to delete multiple at once.

Upvotes: 1

Related Questions