支持不同的JPA生成类型以进行测试/生产 [英] Supporting Different JPA GenerationTypes for Test/Production

查看:72
本文介绍了支持不同的JPA生成类型以进行测试/生产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的生产MySQL系统中将GenerationType.IDENTITY用作主键.但是对于本地开发和测试,我想使用HSQLDB.问题是HSQLDB不支持GenerationType.IDENTITY(至少在Eclipselink中).我尝试设置GenerationType.AUTO,对于HSQLDB,它默认为TABLE,但是不幸的是,对于MySQL,它的功能相同,这不是我想要的.有什么方法可以在persistence.xml中覆盖它吗?我还可以使用其他技巧来使每个环境做正确的事情吗?我没有在XML中设置任何实体配置(全部在批注中),并且我不想更改此设置,因此我正在寻找一种避免这种情况的方法.

解决方案

此处的基本思想是使用一个自定义生成器,该生成器将根据元数据信息在身份和表(或您需要的其他任何策略)之间进行内部切换.

但是,无法使用标准JPA来执行此操作.尽管@GeneratedValue注释确实定义了generator参数,该参数使您可以中有一个示例,说明了如何定义定制生成器.您需要对其进行更改,以在内部创建TableSequence/NativeSequence实例,然后根据 解决方案

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.

这篇关于支持不同的JPA生成类型以进行测试/生产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆