I'm developing a RESTful web application (using hibernate and mysql), specs of which are as below:
- two tables in the database, tableA and tableB.
- tableA has columns named col1A and col2A
- tableB has columns named col1B, col2B and col1A; this last column (col1A) being the foreign key, mapping into the primary key of tableA.
The JAVA classes corresponding to the tables are defined as:
class tableA {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@XmlTransient
private int col1A;
private string col2A;
// getters and setters
}
class tableB {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@XmlTransient
private int col1B;
@XmlTransient
@ManyToOne(cascade=CascadeType.REMOVE)
@JoinColumn(name = "col1A", referencedColumnName = "col1A", insertable = false, updatable = false)
private tableA tableAObj;
private string col2B;
// getters and setters
// There is a getter and setter for the col1A field as well.
}
When I delete a row from the tableA, I assume that the rows in tableB that reference the row being deleted should be deleted by themselves (because of CascadeType.REMOVE). However, I get the following exception:
Cannot delete or update a parent row: a foreign key constraint fails (
pack1.tableB, CONSTRAINTFK27B8B255168D05FOREIGN KEY (col1A) REFERENCEStableA(col1A))
What am I doing wrong?
Thanks.
Update:
Some changes: I've added annotation in tableA like so:
@XmlTransient
@OneToMany(cascade=CascadeType.REMOVE, orphanRemoval=true)
private List<Test> tableB;
Still I get the same exception as before.
I'm removing the row using EntityManger's remove operation:
em.remove(t)
@OnetoMany). And annotate this set@onDelete(action=OnDeleteAction.Cascade)- michikot