'How to delete a child entity in a cascading one-to-many relationship? (JPA with Eclipselink)

Using JPA with EclipseLink, I have a parent and child entity. The bidirectional relationship is Person(one)-Phone(many).

Person:

@Entity
@NamedQueries({
        @NamedQuery(name = "Person.deleteAllRows", query = "DELETE from Person"),
})
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    // ...

    @OneToMany(
            mappedBy = "person",
            cascade = CascadeType.ALL,
            orphanRemoval = true
    )
    private HashSet<Phone> phones = new HashSet<>();

Phone:

@Entity
@NamedQueries({
        @NamedQuery(name = "Phone.deleteAllRows", query = "DELETE from Phone"),
})
public class Phone {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String number;
    // ...


    @ManyToOne
    private Person person;

In my test, I try to delete all parent (Person) rows and expect the child (Phone) rows to be deleted as well:

EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.createNamedQuery("Person.deleteAllRows").executeUpdate();
em.getTransaction().commit();
em.close();

But I get told that a foreign key constraint fails.

Internal Exception: java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`startcode_test`.`PHONE`, CONSTRAINT `FK_PHONE_PERSON_ID` FOREIGN KEY (`PERSON_ID`) REFERENCES `PERSON` (`ID`))
Error Code: 1451
Call: DELETE FROM PERSON

I've tried to make the relationship unidirectional and cascading as well, without luck. What am I missing?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source