DBUnit - violation of integrity constraints: the foreign key is not valid; SYS_FK_10556

I am currently testing code with dbunit (using hsqldb). However, I have a huge problem when initializing db:

here is the code:

/** * 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); } } 

My create statement looks like this:

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

and my startDatabaseRating.xml looks like this:

 <?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> 

When I run the tests, I get:

java.sql.SQLIntegrityConstraintViolationException: integrity violation of restrictions: foreign key is not valid; Table SYS_FK_10556: RATING

Why am I getting this exception because there is still a dataset in the * .xml file. How to solve this problem?

UPDATE:

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

When you insert a rating, the referenced movie must already exist in the movie table. Thus, you are inserting rows in the wrong order.

You need to insert movies first , and then ratings.

 <?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> 
+11
source

I would also recommend that you use regular labels for your columns, especially for the identifier and foreign key , because it is much easier to understand and maintain if another person answers your code someday!

 <?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> 
0
source

All Articles