0
votes

I'm developing a RESTful web application (using hibernate and mysql), specs of which are as below:

  1. two tables in the database, tableA and tableB.
  2. tableA has columns named col1A and col2A
  3. 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, CONSTRAINT FK27B8B255168D05 FOREIGN KEY (col1A) REFERENCES tableA (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)
1
You should create mapping of TableB in TableA (@OnetoMany). And annotate this set @onDelete(action=OnDeleteAction.Cascade) - michikot
@michikot, I'm using entitymanager's remove to remove record from the table: em.remove(t), will the approach you specified work? - AarCee
yes we have use it in our projects.please see my update\ - michikot

1 Answers

0
votes

Got it, added the mappedBy attribute in tableA like so:

@XmlTransient
@OneToMany(cascade=CascadeType.REMOVE, orphanRemoval=true, mappedBy = "tableAObj")
private List<TableB> tableB;