The primary key of a database row is its identity. There are a number of ways dealing with this issue. <> == Natural Keys == ''ToBeWritten'' == Surrogate Keys == ''ToBeWritten'' === GUID strings === ''ToBeWritten'' === Sequence numbers === ''ToBeWritten'' ==== Inserted by code ==== ''ToBeWritten'' ==== Inserted by database ==== This is a cool technique, because it offloads the responsibility of generating a unique key from the code, which shouldn't care about the value, to the database, which is already enforcing the unique constraint. For some databases, there is an option to automatically generate the key. Unfortunately, with this convenience often comes a loss of flexibility. With Microsoft SQLServer 2000, for instance, if you use this facility then DbUnit cannot insert test data. When it tries, the driver throws a !SqlException, "Cannot insert explicit value for identity column in table 'Tablename' when IDENTITY_INSERT is set to OFF." The solution is to manually turn off the key identity flag, run the DbUnit insert, and then turn it back on. DbUnit can restore the contents of the records just fine, once they exist. ==== Inserted by database trigger ==== As mentioned above, some databases offer an ''autonumber'' type to provide numeric primary keys, but with Oracle, you need to [[http://www.jlcomp.demon.co.uk/faq/autonumb.html|use a sequence and a trigger]]. The simplistic way is to do this: {{{ create sequence auto_seq; create trigger aut_bri before insert on auto_numb for each row begin select auto_seq.nextval into :new.n1 from dual; end; }}} but that will get in the way if you try to use DbUnit to insert test data. I recommend {{{ create sequence auto_seq; create trigger aut_bri before insert on auto_numb for each row begin if (:new.n1 is null) then select auto_seq.nextval into :new.n1 from dual; end if end; }}} instead. This allows you to specify a particular key when desired. To avoid conflicts between your specified test keys and sequence generated keys, use negative values for the specified ones.