在不同情况下使用不同的休眠用户类型 [英] Using Different Hibernate User Types in Different Situations
问题描述
我使用Hibernate + JPA作为我的ORM解决方案。
I am using Hibernate + JPA as my ORM solution.
我使用HSQL的单元测试和PostgreSQL作为真正的数据库。
I am using HSQL for unit testing and PostgreSQL as the real database.
我希望能够使用的Postgres的原生 UUID 与Hibernate类型,并使用UUID在其字符串重新presentation与HSQL的单元测试(因为HSQL没有一个UUID类型)。
I want to be able to use Postgres's native UUID type with Hibernate, and use the UUID in its String representation with HSQL for unit testing (since HSQL does not have a UUID type).
我使用的是XML持久性与Postgres的和HSQL的单元测试不同的配置。
I am using a persistence XML with different configurations for Postgres and HSQL Unit Testing.
下面是我已经休眠看到我的自定义用户类型:
Here is how I have Hibernate "see" my custom UserType:
@Id
@Column(name="UUID", length=36)
@org.hibernate.annotations.Type(type="com.xxx.UUIDStringType")
public UUID getUUID() {
return uuid;
}
public void setUUID(UUID uuid) {
this.uuid = uuid;
}
和伟大工程。但是,我需要的是换出注解的com.xxx.UUIDStringType的一部分在XML或从无需重新编译更改的属性文件的能力。
and that works great. But what I need is the ability to swap out the "com.xxx.UUIDStringType" part of the annotation in XML or from a properties file that can be changed without re-compiling.
任何想法?
推荐答案
这问题真的老了,并已回答了很长一段时间,但最近我发现自己在这个相同的情况下,发现了一个很好的解决方案。对于初学者来说,我发现Hibernate有三种不同的内置UUID类型实现:
This question is really old and has been answered for a long time, but I recently found myself in this same situation and found a good solution. For starters, I discovered that Hibernate has three different built-in UUID type implementations:
-
二进制UUID
:存储UUID为二进制 -
UUID-CHAR
:存储UUID作为一个字符序列 -
PG-UUID
:使用本地Postgres的UUID类型
binary-uuid
: stores the UUID as binaryuuid-char
: stores the UUID as a character sequencepg-uuid
: uses the native Postgres UUID type
这些类型在默认情况下注册,并可以使用 @Type
标注某一领域,例如指定。
These types are registered by default and can be specified for a given field with a @Type
annotation, e.g.
@Column
@Type(type = "pg-uuid")
private UUID myUuidField;
还有也的在方言
覆盖默认类型的机制。因此,如果最终部署是跟一个Postgres数据库,但我们的单元测试使用HSQL,可以覆盖 PG-UUID
键入阅读写作/写入字符数据一个自定义的话,像这样:
There's also a mechanism for overriding default types in the Dialect
. So if the final deployment is to talk to a Postgres database, but we the unit tests use HSQL, you can override the pg-uuid
type to read/write character data by writing a custom dialect like so:
public class CustomHSQLDialect extends HSQLDialect {
public CustomHSQLDialect() {
super();
// overrides the default implementation of "pg-uuid" to replace it
// with varchar-based storage.
addTypeOverride(new UUIDCharType() {
@Override
public String getName() {
return "pg-uuid";
}
});
}
}
现在只需插入自定义的方言,而在 PG-UUID
类型是在两个环境中使用。
Now just plug in the custom dialect, and the the pg-uuid
type is available in both environments.
这篇关于在不同情况下使用不同的休眠用户类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!