users@jpa-spec.java.net

[jpa-spec users] Schema generation with existing EMF

From: Christian Bauer <christian.bauer_at_gmail.com>
Date: Sun, 24 Mar 2013 08:49:34 +0100

I've been running into a conceptual issue with schema generation in JPA 2.1 and how unit tests are typically organized.

Let's say you want a clean database for every unit test method. I prefer to create the schema in the database before every test method, and then drop it after the test method completes.

I have a single EntityManagerFactory for the whole test class, it can be shared by every test method. This is possible with the Hibernate API, the schema generator uses an existing EMF configuration to produce the create/drop scripts.

With the static Persistence.generateSchema() in 2.1 this approach doesn't work. Calling generateSchema() internally builds a new EMF every time.

One of the problems is that you get new automatically generated foreign key names every time you call generateSchema(). The "drop" action therefore always fails, unless you define all foreign key names in your metadata. There could be other automatically generated artifact names, so the "drop" action in general, if called from a static context, is not useful during development.

The current solution then is to specify "drop-and-create" and to build and close an EMF for every unit test method. This means starting and stopping the persistence provider for every test method, slowing down test runs significantly.

A better solution would be an additional Persistence.generateSchema(EMF, properties) method that accepts an existing EMF and some "override" properties.