数据集的DBUnit顺序

时间:2017-02-26 13:45:36

标签: dbunit spring-test-dbunit

我有以下非常奇怪的DBUnit数据集:

<persons id = "1"
         first_name ="TestName99"
         second_name = "TestSecondName"
         father_name = "TestFatherName"
         phone_number = "123456789"
         date_of_birth = "1985-12-12 00:16:14"
         role = "ROLE_OWNER"
         date_of_creation = "2016-09-23 23:09:28"
         enable = "1" />

<carwash id = "1"
         name = "TestCarWash"
         address = "test car wash address "
         phone_number = " 123456789"
         box_count = "5"
         first_shift = "08:00:00"
         second_shift = "20:00:00"
         created_by = "1"
         date_of_creation = "2016-09-23 23:09:28"
         enable = "1" />

<persons id = "2"
         first_name ="TestName100"
         second_name = "TestSecondName"
         father_name = "TestFatherName"
         phone_number = "123456789"
         date_of_birth = "1985-12-12 00:16:14"
         role = "ROLE_WASHERMAN"
         date_of_creation = "2016-09-23 23:09:28"
         carwash = "1"
         enable = "1" />

最奇怪的是persons表有carwash的外键但是这个列可以为空(因此你找不到carwash和{id=1的人carwash 1}}表在persons

中有FK到create_by

此方案导致在DB中放置数据的特殊顺序。据我所知,DBUnit默认情况下不会根据数据集中提到的值对DB中的值进行设置。因此,当该数据集执行时,它会导致异常

MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`test_pitstop`.`persons`, CONSTRAINT `persons_ibfk_1` FOREIGN KEY (`carwash`) REFERENCES `carwash` (`id`))

是否有任何方法可以推动DBUnit按照字符串顺序将数据放入数据库中,如xml中所述?

2 个答案:

答案 0 :(得分:1)

在dataset.xml文件中,您必须以正确的顺序指定表,这意味着首先是基本表,然后是相关表。通过这种方式并使用 DatabaseOperation.CLEAN_INSERT ,表格也将被正确删除(首先是相关表格,然后是基本表格)。

您的xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<dataset>

<carwash id = "1"
     name = "TestCarWash"
     address = "test car wash address "
     phone_number = " 123456789"
     box_count = "5"
     first_shift = "08:00:00"
     second_shift = "20:00:00"
     created_by = "1"
     date_of_creation = "2016-09-23 23:09:28"
     enable = "1" />

<persons id = "1"
     first_name ="TestName99"
     second_name = "TestSecondName"
     father_name = "TestFatherName"
     phone_number = "123456789"
     date_of_birth = "1985-12-12 00:16:14"
     role = "ROLE_OWNER"
     date_of_creation = "2016-09-23 23:09:28"
     enable = "1" />

<persons id = "2"
     first_name ="TestName100"
     second_name = "TestSecondName"
     father_name = "TestFatherName"
     phone_number = "123456789"
     date_of_birth = "1985-12-12 00:16:14"
     role = "ROLE_WASHERMAN"
     date_of_creation = "2016-09-23 23:09:28"
     carwash = "1"
     enable = "1" />

</dataset>

希望这有帮助。

答案 1 :(得分:0)

根据错误消息,它是数据库中的SQL约束违规,而不是dbUnit问题。 Persons.carwash是一个不可废除的列,还是需要来自Carwash的FK? dbUnit不能覆盖数据库约束,就像您自己的代码不能一样。