views:

325

answers:

2

I want to use GenerationType.IDENTITY for primary keys in my production MySQL system. But for local development and testing, I'd like to use HSQLDB. The problem is that HSQLDB doesn't support GenerationType.IDENTITY (at least with Eclipselink). I tried setting GenerationType.AUTO, which defaults to TABLE for HSQLDB, but unfortunately it does the same for MySQL, which is not what I want. Is there some way to override this in persistence.xml? Is there some other trick I can use so that each environment does the right thing? I don't have any entity configuration set up in XML (it is all in annotations) and I do not want to change this, so am looking for a way that avoids this.

+2  A: 

The basic idea here is to use a custom generator that would internally switch between identity and table (or whatever else strategies you need) based on metadata information.

There's no way to do this using standard JPA, however. While @GeneratedValue annotation does define generator parameter that enables you to specify a custom generator it does not provide any mechanisms for writing one (only allowing you to use built-in Table / Sequence generators).

It's up to a specific JPA provider to (not) implement this functionality. EclipseLink wiki has an example of how custom generator may be defined. You'll need to alter it to create TableSequence / NativeSequence instances internally and switch between the two based on session.getPlatform().

Disclaimer: I haven't tried the above using EclipseLink; I did something very similar in Hibernate, though.

ChssPly76
+1  A: 

HSQLDB obviously does itself support IDENTITY columns (definitely in v1.8), so this is a flaw in EclipseLink. For example, DataNucleus provides IDENTITY support for HSQLDB.

Specifying using XML has its benefits for cross-datastore deployment, as you clearly know.

DataNucleus
Interesting. I'll file an issue with the Eclipselink people. This would certainly make things simpler for me.
Tim