Generating db for unit tests is pretty easy in JPA 2.1 or rather as easy as it was but a lot more portable an with more management options. We have a few new entries available in persistence.xml (8.2.1.9 properties of JPA 2.1 spec), relevant to db creation are:

  • javax.persistence.schema-generation.create-script-source – this entry points jpa provider to script used when creating db
  • javax.persistence.schema-generation.drop-script-source – this entry points jpa provider to script used when tearing down db
  • javax.persistence.sql-load-script-source – this entry points jpa provider to script that is to load the data
  • javax.persistence.schema-generation.database.action – what action should be done for database – is the JPA provider to create database, drop it or both (drop-and-create) or maybe none?
  • javax.persistence.schema-generation.scripts.action – as above but used for generation of script files
  • javax.persistence.schema-generation.create-source – what source of information should JPA provider use when creating database – scripts, metadata or maybe scripts-then-metadata or metadata-then-script
  • javax.persistence.schema-generation.drop-source – as above but for dropping database
  • javax.persistence.schema-generation.scripts.create-target – target location for create instructions script
  • javax.persistence.schema-generation.scripts.drop-target- target location for drop instructions script

Example configuration:

In the example above H2 database is created in Oracle compatibility mode. Scripts are generated in root folder of project but not used to create or drop database. I used them to make creation of load script easier. Load script is read from src/main/resources 🙂 Hibernate will also read it from root folder, but EclipseLink refuses to do so.

Interesting option is using metadata to create DB and then ddl script to add some specific details or add stored procedures (yes, you could do it e.g. in hibernate using hibernate.cfg.xml but current solution is more portable).

Important detail – notice that all classes are listed in Persistence Unit. Some providers will support class detection when PU is bootstrapped in Java SE environment, some do not. It is safer to list classes. Code that uses unit tests and bootstraps database can be downloaded from GitHub.

If portability is not connected to losing some functionality than why not to use this option ? On the other hand if the price would be to sacrifice some required and well designed, written and maintained functionality that better solution would be to encapsulate the provided dependent part than to use the portable mechanism.

Have en dejlig dag!