DBUnit - 完整性约束违规:外键无动作; SYS_FK_10556

时间:2013-01-05 11:43:04

标签: java database eclipse unit-testing dbunit

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

这里是代码:

/**
     * 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语句如下:

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表:   RATING

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

更新

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

2 个答案:

答案 0 :(得分: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> 

答案 1 :(得分:0)

另外,我建议你为你的专栏使用常规标签,特别是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>