1
當試圖刪除包含OneToMany關係的對象時,我遇到了約束問題,該對象不應該發生。我已經設置了cascade = CascadeType.ALL
,嘗試添加Hibernate特定的@Cascade
註釋,嘗試重建一個新的數據庫,並且我甚至創建了最低的示例,下面的示例都失敗了。級聯不能使用Spring Data刪除JPA存儲庫
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 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
}
測試
@Entity
public class Bar {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@ManyToOne
private Foo foo;
// 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關係上設置了級聯。爲什麼這是失敗的?
仍然有'orphanRemoval'錯誤。 –
也可以在測試中嘗試'foo.getBars().add(bar)'以確保雙向關係正確建立。 – Sergio
修復它。這是否意味着我需要將關聯添加到兩個對象以保持雙向關係?我想如果我將'Foo'對象添加到'Bar'對象,它會自動創建一個雙向關係。 –