简体   繁体   中英

How to automatically remove child entities?

I'd like to remove entities from my table and have it auto-removed any entities that are childs of it.

Example:

class User {
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval=true)
    @OnDelete(action = OnDeleteAction.CASCADE)
    List<Address> addresses;
}

When I remove a User that has no address, everything works fine. Also removing an address without removing the user works.

But: If I try to remove a user that has still some addresses, I'm getting org.hsqldb.HsqlException :

integrity constraint violation: foreign key no action; FK_ADDRESS_USER_ID table: ADDRESS

What might be wrong here? Or is this not supported and I have to explicitly remove all contained Address objects first before deleting a user?

I believe you have a problem with a foreign key constraint. Use a DB tool like Aqua Data Studio or similar (you can probably also do this in your IDE, in Eclipse - Data Source Explorer view), to show the create script for your ADDRESS table. It should contain something like this:

ALTER TABLE TESTSCHEMA.ADDRESS
    ADD CONSTRAINT FK1ED033D4E91AAFD9
    FOREIGN KEY(FK_ADDRESS_USER_ID)
    REFERENCES TESTSCHEMA.USER(ID)
    ON DELETE CASCADE

The point being the ON DELETE CASCADE part in your case. If this is missing or is different, that probably is what is causing the problem. If the table is auto-generated by Hibernate, this constraint should be valid, but keep in mind that there are differences between databases. It could be that the table was generated before the Hibernate's @OnDelete annotation was added, so now you are getting the "foreign key no action" integrity constraint violation.

Not related to the issue, but do note that orphanRemoval=true will try to remove the address from the database , when it is removed from the collection in the User entity.

Also, check this out for details on Hibernate's support for database ON DELETE CASCADE constraint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM