级联无法使用 Spring Data JPA 存储库进行删除

Cascading not working on delete with Spring Data JPA Repositories

我在尝试删除包含不应发生的 OneToMany 关系的对象时遇到约束问题。我已经设置 cascade = CascadeType.ALL,尝试添加特定于 Hibernate 的 @Cascade 注释,尝试重建一个新数据库,我什至创建了下面的最小示例,所有这些都失败了。

Cannot delete or update a parent row: a foreign key constraint fails (`test-db`.`bar`, CONSTRAINT `FKdvoqij212wwl2bf14kwo55h55` FOREIGN KEY (`foo_id`) REFERENCES `foo` (`id`))

要级联的对象

@Entity
public class Bar {

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

    @ManyToOne
    private Foo foo;

    // Constructor, getters and setters omitted
}

Class包含级联

@Entity
public class Foo {

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

    @OneToMany(mappedBy = "foo", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Bar> bars;

    // Constructor, getters and setters omitted
}

测试:

// Spring Data JPA Repositories (extend CrudRepository)
@Autowired private FooRepository fooRepository;
@Autowired private BarRepository barRepository;

@Test
public void test() {
    final Foo foo = new Foo();
    fooRepository.save(foo);

    final Bar bar = new Bar();
    bar.setFoo(foo);
    barRepository.save(bar);

    fooRepository.delete(foo);
}

上述测试失败。我希望能够删除 Foo 而不必删除所有关联的 Bar 对象,因为在 OneToMany 关系上设置了级联。为什么会失败?

尝试@OneToMany(mappedBy = "foo", cascade = CascadeType.ALL, orphanRemoval = true)