本文介绍了将DbUnit与没有主键的表一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置单元测试环境以使用DbUnit.

I'm attempting to set up my unit testing environment to use DbUnit.

我遇到了一些问题,因为我要控制的表没有主键.我收到了org.dbunit.dataset.NoPrimaryKeyException.

I'm having a few problems as the tables which I am attempting to control do not have primary keys. I have been getting a org.dbunit.dataset.NoPrimaryKeyException.

我已按照此处 http://dbunit.wikidot.com/noprimarykeytable 的步骤进行操作,但是该怎么做我使用:

I have followed the steps here http://dbunit.wikidot.com/noprimarykeytable but how do I use:

connection.getConfig().setProperty("http://www.dbunit.org/properties/primaryKeyFilter", new MyPrimaryKeyFilter("A1"));

我的每张桌子都是

例如,我有以下数据库:

For example, I have the following database:

CREATE TABLE `NO_PK1` (
  `A1` int(11) NOT NULL,
  `A2` varchar(50) default NULL
);

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
  <NO_PK1 A1="1" A2="Test1" />
  <NO_PK1 A1="2" A2="Test2" />
  <NO_PK1 A1="3" />
</dataset>

CREATE TABLE `NO_PK2` (
  `B1` int(11) NOT NULL,
  `B2` varchar(50) default NULL
);

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
  <NO_PK2 B1="1" B2="Test1" />
  <NO_PK2 B1="2" B2="Test2" />
  <NO_PK2 B1="3" />
</dataset>

CREATE TABLE `NO_PK3` (
  `C1` int(11) NOT NULL,
  `C2` varchar(50) default NULL
);

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
  <NO_PK3 C1="1" C2="Test1" />
  <NO_PK3 C1="2" C2="Test2" />
  <NO_PK3 C1="3" />
</dataset>

在这种情况下如何重写connection.getConfig().setProperty("http://www.dbunit.org/properties/primaryKeyFilter", new MyPrimaryKeyFilter("A1"));?

How do I rewrite connection.getConfig().setProperty("http://www.dbunit.org/properties/primaryKeyFilter", new MyPrimaryKeyFilter("A1")); in this instance?

非常感谢您的任何建议.

Many thanks for any advice.

推荐答案

您需要确保MyPrimaryKeyFilter处理架构中的所有表.在该示例中,只有一个表,因此提供的简单过滤器类可以正常工作.在您的情况下,我可能会将该类更改为采用包含表的Map-> pk列名称映射:

You need to make sure that your MyPrimaryKeyFilter handles all the tables in your schema. In the example, there is only one table, so the simple filter class provided works fine. In your case, I would probably change that class to take a Map containing table -> pk column name mappings:

class MyPrimaryKeyFilter implements IColumnFilter {
        private Map<String, String> pseudoKey = null;

        MyPrimaryKeyFilter(Map<String, String> pseudoKey) {
            this.pseudoKey = pseudoKey;
        }

        public boolean accept(String tableName, Column column) {
            return column.getColumnName().equalsIgnoreCase(pseudoKey.get(tableName));
        }

    }

,然后使用{NO_PK1-> A1},{NO_PK2-> B1}和{NO_PK3-> C1}条目设置地图.

and then set up the map with {NO_PK1 -> A1}, {NO_PK2 -> B1}, and {NO_PK3 -> C1} entries.

这篇关于将DbUnit与没有主键的表一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 10:56