简体   繁体   中英

Cannot delete a record with OneToMany relation

When I delete a record in a table, related record should be deleted in another table. But I receive instead:

java.sql.BatchUpdateException: Batch entry 0 update child_table set parent_table_id=null where parent_table_id=63 was aborted

The exception above is thrown against the following settings:

@OneToMany(cascade = javax.persistence.CascadeType.ALL, targetEntity = ChildTable.class)
@JoinColumn(name = "parent_table_id")
@org.hibernate.annotations.Fetch(FetchMode.SUBSELECT)
public List<ChildTable> getTables() {
    return tables;
}

If I'm not mistaken, with such annotations, when a record is deleted in ParentTable, corresponding relation should be deleted in Child one. It tries to become "null" (because corresponding record exists no more) before complete deletion. This id column is "not null". When I make it be "null" (just for testing this case) everything works correctly.

Could you help me understand what is the real problem behind this?

Thank you in advance.

I usually don't use annotations. I prefer hbm mapping files so I can tell you some possible solutions with hbm mappings. :) I think you need to add inverse=true in your parent one-to-many relationship. Always put inverse=true in your parent collections . For annotation equivalent of inverse=true please see this .

If this doesn't work, I know it would not be a good solution, you can give a try with not-found="ignore" or @NotFound(action=NotFoundAction.IGNORE) in the one-to-many relationship in parent. Eventually, it has same effect as making not-null=false for the foreign key column in database.

One of the responders gave correct answer, but he deleted it. I had to use hibernate Cascade annotation instead of JPA one. It didn't work for me because the problem was a little bit deeper than just usage of JPA and hibernate annotations together. Mapper class for ChildTable had parent_table_id of int type instead of a ParentTable class type the id field is mapped in. So I changed it from:

@Entity
@Table(name = "child_table")
public class ChildTable {

private int id;
private int parent_table_id;
...

to

@Entity
@Table(name = "child_table")
public class ChildTable {

private int id;
private ParentTable parent_table;
...

Surely some additional changes (connected to this one) were made and deletion started to work as expected.

So, if you have corresponding error during deletion of an entity in one-to-many relation and everything is correct with annotations usage, check the types, your fields are of, in mapper-classes :)

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