JPA呼吸及其测试

发布于 2025-01-20 00:01:44 字数 904 浏览 0 评论 0原文

这更多的是一个关于概念的问题,而不是我面临的错误。 所以这里我有两个 JPA 存储库引用数据库中的两个表 教师 - 具有对 Departmentid 的外键引用 部门 - 包含部门信息

现在要测试部门存储库集成测试,我必须删除教师的所有条目,然后删除部门。我知道我有一个对部门的外键引用,因此我无法删除教师表正在使用的部门内的任何条目。但是,当我运行此测试时,教师表中没有保存或插入任何内容,但我仍然收到 DataIntergityViolationException。为什么要强制删除教师表条目,即使它手动为空? 找不到任何与我的疑问相关的内容。 我正在针对 H2 等内存数据库运行测试。

@SpringBootTest(webEnvironment = RANDOM_PORT)
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = {
  "spring.datasource.url=jdbc:sqlserver://localhost:1433;loginTimeout=30;",
  "spring.datasource.username="random",
  "spring.datasource.password="random"
})
public class DepartmentRepositoryIntegrationTest {

  @Autowired
  private DepartmentRepository departmentRepository;

  @Autowired
  private FacultyRepository facultyRepository;

  @Before
  public void setUp() {
    departmentRepository.deleteAll();
    facultyRepository.deleteAll();
  }

This is more of a question regarding concept rather than an error I am facing.
So here I have two JPA respositories refereing to two tables in database
Teacher - has foreign key reference to departmentid
Depeartment - contains depeartment infos

Now to test the DepartmentRepositoryIntegrationTest I have to delete all the entries of teachers and then the depeartments. I understand I have a foreign key reference to departments so I cant delete any entry inside the department which is being consumed by the Teacher table. But When I was running this test there was nothing saved or inserted in the teachers table still I was getting DataIntergityViolationException. Why was there such enforcement to delete teachers table entries even though it was empty manually???
Couldnt find anything relevant to my doubt.
I am running the tests against the inmemory database like H2.

@SpringBootTest(webEnvironment = RANDOM_PORT)
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = {
  "spring.datasource.url=jdbc:sqlserver://localhost:1433;loginTimeout=30;",
  "spring.datasource.username="random",
  "spring.datasource.password="random"
})
public class DepartmentRepositoryIntegrationTest {

  @Autowired
  private DepartmentRepository departmentRepository;

  @Autowired
  private FacultyRepository facultyRepository;

  @Before
  public void setUp() {
    departmentRepository.deleteAll();
    facultyRepository.deleteAll();
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文