【发布时间】:2019-10-28 05:41:54
【问题描述】:
我有单向相关实体:
@Entity
public class Book {
private String isbn;
}
@Entity
private class Recommentation {
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "book_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private Book book;
}
还有以下测试:
@RunWith(SpringRunner.class)
@DataJpaTest
public class BookRepositoryTest {
@Autowired
private TestEntityManager testEntityManager;
@Autowired
private BookRepository bookRepository;
@Test
public void delete() {
// given
String isbn = "isbn-1";
Book book = new Book();
book.setIsbn(isbn);
testEntityManager.persist(book);
Recommendation recommendation = new Recommendation();
recommendation.setBook(book);
testEntityManager.persist(recommendation);
// when
bookRepository.deleteBookByIsbn(book.getIsbn());
// then
assertThat(testEntityManager.find(Book.class, book.getId())).isNull();
assertThat(testEntityManager.find(Recommendation.class, recommendation.getId())).isNull();
}
}
@OnDelete(action = OnDeleteAction.CASCADE) 在不是从测试中调用此代码时效果很好,但在测试中我得到了建议没有被书删除的异常。
我还尝试从为休眠查询记录的 sql 中获取任何信息,但我看不到任何用于此测试的 delete 语句。
我不想对实体使用双向链接,只是尝试了解如何解决这个具体问题或以某种方式对其进行调试。
【问题讨论】:
-
也许应该在一个事务中:stackoverflow.com/questions/17263475/…
标签: hibernate spring-boot jpa spring-data-jpa spring-test