はじめに
想定状況
以下のようなデータを投入することを想定しています。
id
は自動採番になっているカラムとします。
test.csv
id,name,age
1,bob,26
2.alice,24,
投入しようとすると、以下のようなエラーが出てきました。
Cannot insert explicit value for identity column in table 'table_name when IDENTITY_INSERT is set to OFF.
解決策
DbUnitのFAQに対処方が記載されていました。
Can I use DbUnit with IDENTITY or auto-increment columns?
Many RDBMSes allow IDENTITY and auto-increment columns to be implicitly overwritten with client values. DbUnit can be used with these RDBMS natively. Some databases, like MS SQL Server and Sybase, need to explicitly activate client values writing. The way to activate this feature is vendor-specific.
DbUnit provides this functionality for MS SQL Server with the InsertIdentityOperation class.
InsertIdentityOperation class
を使えば良いみたいです。
データ投入時の操作を以下のようにします。
Test.java
new InsertIndentityOperation(DatabaseOperation.CLEAN_INSERT).execute(connection,dataSet);