5

我目前正在使用 dbunit(使用 hsqldb)进行编码测试。但是,我在初始化数据库时遇到了一个巨大的问题:

这是代码:

/**
     * Init before a test starts
     */
    @Before
    public void initialise() {
        IDataSet dataSetRating = null;
        IDataSet dataSetMovie = null;

        log.info("enter init test");

        try {
            con = datasource.getConnection();
            icon = new DatabaseConnection(con);
            File rating = new File("./src/test/resources/startDatabaseRating.xml");         
            dataSetRating = new FlatXmlDataSetBuilder().build(rating);
            DatabaseOperation.CLEAN_INSERT.execute(icon, dataSetRating);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e);
            System.exit(-1);
        }
    }

我的创建语句如下所示:

CREATE TABLE Rating
(
    rid INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    mid INTEGER FOREIGN KEY REFERENCES Movie(movieId), 
    rating INTEGER NOT NULL, 
);

我的 startDatabaseRating.xml 看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <Rating rid="0" mid="0" rating="1" />
    <Rating rid="1" mid="0" rating="2" />
    <Rating rid="2" mid="0" rating="3" />
    <Rating rid="3" mid="0" rating="4" />

    <Movie movieid="0" title="Movie1" moviePath="C" />
    <Movie movieid="1" title="Movie2" moviePath="D" />
</dataset> 

当我运行测试时,我得到:

java.sql.SQLIntegrityConstraintViolationException:完整性约束违规:外键无动作;SYS_FK_10556 表:评级

为什么会出现此异常,因为 *.xml 文件中仍有数据集。如何解决这个问题?

更新:

CREATE TABLE Movie
(
    movieId INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    moviePath VARCHAR(500) NOT NULL
);
4

2 回答 2

12

插入评分时,引用的电影必须已存在于movie表中。因此,您以错误的顺序插入行。

您需要先插入电影,然后再插入收视率。

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <Movie movieid="0" title="Movie1" moviePath="C" />
    <Movie movieid="1" title="Movie2" moviePath="D" />

    <Rating rid="0" mid="0" rating="1" />
    <Rating rid="1" mid="0" rating="2" />
    <Rating rid="2" mid="0" rating="3" />
    <Rating rid="3" mid="0" rating="4" />
</dataset> 
于 2013-01-05T12:11:06.507 回答
1

此外,我建议您为列使用常规标签,尤其是 id 和外键,因为如果有一天另一个人负责您的代码,它更容易理解和维护!

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <Movie id="0" title="Movie1" moviePath="C" />
    <Movie id="1" title="Movie2" moviePath="D" />

    <Rating id="0" movie_id="0" rating="1" />
    <Rating id="1" movie_id="0" rating="2" />
    <Rating id="2" movie_id="0" rating="3" />
    <Rating id="3" movie_id="0" rating="4" />
</dataset> 
于 2018-04-03T14:48:02.487 回答