![](/img/trans.png)
[英]How to setup/teardown dbunit dataset without using static @BeforeClass
[英]How to do a custom database setup/teardown in Spring Test Dbunit?
我想知道如何创建自定义设置/拆卸,主要是为了解决Cyclyc参考问题,在这里我可以使用Spring Test Dbunit http://springtestdbunit.github.io/spring-test-dbunit/index.html插入自定义SQL命令。
有没有我可以使用的注释,或者如何对其进行自定义?
dbunit需要按顺序插入语句(xml行),因为它们是顺序执行的。 没有或魔术参数或注释,因此dbunit可以自动解析您的Cyclyc参考或外键。
如果您的数据集包含许多带有外键的表,则是我能实现的最自动化的方法:
用很少的记录填充数据库。 在您的示例中:Company,CompanyConfig,并确保满足外键。
使用dbunit Export工具提取数据库样本。
这是您可以使用的片段:
IDatabaseConnection connection = new DatabaseConnection(conn, schema);
configConnection((DatabaseConnection) connection);
// dependent tables database export: export table X and all tables that have a // PK which is a FK on X, in the right order for insertion
String[] depTableNames = TablesDependencyHelper.getAllDependentTables(connection, "company");
IDataSet depDataset = connection.createDataSet(depTableNames);
FlatXmlWriter datasetWriter = new FlatXmlWriter(new FileOutputStream("target/dependents.xml"));
datasetWriter.write(depDataset);
运行此代码后,将在“ dependents.xml”中设置dbunit数据,并固定所有循环引用。
在这里,我粘贴了完整的代码 :还可以查看有关如何导出数据的dbunit doc 。
当前没有可以使用的注释,但是您可以创建DbUnitTestExecutionListener
的子类,并在beforeTestMethod
添加自定义逻辑。 或者,您可以创建自己的TestExecutionListener
并在DbUnitTestExecutionListener
之前DbUnitTestExecutionListener
排序。
另一个可能更好的解决方案是重新设计数据库以消除周期。 你也许可以从下降参考company
于company_config
,并加入到一个唯一索引company_id
在company_config
表:
+------------+ 1 0..1 +--------------------------------+ | company |<---------| company_config | +------------+ +--------------------------------+ | company_id | | config_id | | ... | | company_id (fk, notnull, uniq) | +------------+ +--------------------------------+
与其查看company.config_id
来获取配置,不如select * from company_config where company_id = :id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.