Supporting Different JPA GenerationTypes for Test/Production

隐身守侯 提交于 2020-01-14 10:34:29

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/1689553/supporting-different-jpa-generationtypes-for-test-production

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!