[英]How can I add my own EnumValueMapperSupport
I'm trying to persist some enum
s in Hibernate and it looks like my two options for built in support are to use the name of the enum, which I would rather not do because it's string based instead of int based, or the ordinal of the enum, which I would rather not do because if I add one of the enum values at the top of the class later on, I break everything down the line. 我试图在Hibernate中保留一些
enum
,并且看起来我的两个内置支持选项是使用enum的名称,我宁愿不这样做,因为它是基于字符串的,而不是基于int的或枚举,我不愿意这样做,因为如果稍后在类的顶部添加枚举值之一,则会将所有内容分解。
Instead, I have an interface called Identifiable
that has public int getId()
as part of its contract. 相反,我有一个名为
Identifiable
的接口,该接口的合同中包含public int getId()
。 This way, the enums I want to persist can implement Identifable
and I can know that they'll define their own id. 这样,我要保留的枚举可以实现
Identifable
并且我知道它们将定义自己的ID。
But when I try to extend EnumValueMapperSupport so I can utilize this functionality, I'm greeted with errors from the compiler because the EnumValueMapper interface and the EnumValueMapperSupport class are not static, and thus are expected to be locked into a given EnumType object. 但是,当我尝试扩展EnumValueMapperSupport以便可以利用此功能时,由于EnumValueMapper接口和EnumValueMapperSupport类不是静态的,因此希望将其锁定在给定的EnumType对象中,因此会遇到来自编译器的错误。
How can I extend this functionality in Hibernate, short of rewriting a bunch of Hibernate code and submitting a patch. 我如何在Hibernate中扩展此功能,而无需重写一堆Hibernate代码并提交补丁。 If I can't, is there another way to somehow store an enum based on something other than the ordinal or name, but instead on your own code?
如果我做不到,是否有另一种方式可以基于序数或名称之外的其他方式而不是根据您自己的代码存储枚举?
In a related thought, has anyone personally been down this road and decided "let's see how bad the name mapping is" and just went with name mapping because it wasn't that much worse performance? 在一个相关的思想中,是否有人亲自决定“让我们看看名称映射有多糟糕”,并选择名称映射,因为它没有那么糟糕的性能? Like, is it possible I'm prematurely optimizing here?
就像,我可能在这里过早优化吗?
I'm working against Hibernate version 5.0.2-final. 我正在使用Hibernate 5.0.2-final版本。
At least for Hibernate 4.3.5 the EnumValueMapper
is static - although private. 至少对于Hibernate 4.3.5,
EnumValueMapper
是静态的-尽管是私有的。
But you can extend EnumValueMapperSupport
in an extension of EnumType
: 但是您可以在
EnumType
的扩展中扩展EnumValueMapperSupport
:
public class ExampleEnumType extends EnumType {
public class ExampleMapper extends EnumValueMapperSupport {
...
}
}
To create an instance of this mapper you need an instance of your EnumType
: 要创建此映射器的实例,您
EnumType
的实例:
ExampleEnumType type = new ExampleEnumType();
ExampleMapper mapper = type.new ExampleMapper();
Or you create it inside your type: 或者在您的类型内创建它:
public class ExampleEnumType extends EnumType {
public class ExampleMapper extends EnumValueMapperSupport {
...
}
public ExampleMapper createMapper() {
return new ExampleMapper();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.