更新时间:2023-09-09 10:06:46
重做:好的,我很抱歉,我对您的问题不够了解.答案虽然很简单,但这次我实际尝试过.您需要从POJO中的父项中删除该子项,然后重新保存没有该子项的父项.参见下面的注释代码:
REDO: Okay, my apologies, I didn't look close enough at your question. The answer though is simple enough, and this time I actually tried it. You need to remove the child from the parent in the POJO and resave the parent without the child. See commented code below:
List<Book> books = new ArrayList<Book>();
Book book = new Book();
books.add(book);
Author author = new Author();
author.setBooks(books);
authorRepository.save(author);
Author a =authorRepository.findAll().iterator().next();
Book b = a.getBooks().get(0);
bookRepository.delete(b);
// REMOVE FROM PARENT
a.getBooks().remove(0);
authorRepository.save(a);
a = authorRepository.findAll().iterator().next();
System.out.println(a);
如果您担心应该保持的一致性,只需从作者POJO中删除该书,然后在保存作者时,cascade=CascadeType.ALL
将为您传播删除该书.例如:
If you're worried about consistency, which you should be, simply delete the book from the author POJO and when you save author the cascade=CascadeType.ALL
will propagate the delete the book for you. E.g.:
Author a =authorRepository.findAll().iterator().next();
a.getBooks().remove(0);
authorRepository.save(a);
// NO BOOK
a = authorRepository.findAll().iterator().next();
System.out.println(a);