尝试删除包含不应发生的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
}
包含级联的类
@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关系上设置了级联。为什么这会失败?
答案 0 :(得分:1)
尝试@OneToMany(mappedBy = "foo", cascade = CascadeType.ALL, orphanRemoval = true)