0

I have two entities using Spring and Hibernate

Entity A:

@Entity
@Table(name = "A")
public class A {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @OneToOne(cascade = CascadeType.ALL, mappedBy = "a")
    private B b;

Here i have a one to one relationship with Entity B, the owner of the relationship is Entity A.

Entity B:

@Entity
public class B{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @OneToOne
    @JoinColumn(name = "a_ID")
    private A a;

Saving the entities gives no problem. Entity B gets the ID of entity A in the Database. But when i delete Entity A, I also want to delete Entity B that belongs to A.

When I delete i get the error:

MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails

I think my declarations in my entities are correct. What is the problem here?

Edit

When I inspect the table of Entity B and specifically the Foreign key to Entity A it says Restricted on Update en on Delete

Urban
  • 585
  • 2
  • 13
  • 28

1 Answers1

0

set orphanRemoval property to true in class A

like this: @OneToOne(mappedBy = "a", cascade = CascadeType.ALL, orphanRemoval = true)

mrkernelpanic
  • 4,268
  • 4
  • 28
  • 52
priyas
  • 415
  • 1
  • 8
  • 29
  • Do you have remove method for child entity in parent class ? – priyas Oct 17 '17 at 10:35
  • Yes i have put orphanRemoval = true in Entity A. And Entity A is the parent if i understand you correctly. – Urban Oct 17 '17 at 10:36
  • you should have add and remove entity method in class A like this : public void removeB() { if (b!= null) { b.setA(null); } this.b= null; } – priyas Oct 17 '17 at 10:40