问题描述
Hibernate 提供了 @Enumerated
注释,它支持使用 ORDINAL
或 STRING
两种类型的 Enum
映射.当我们使用 EnumType.STRING
映射时,它采用 Enum
的名称"而不是 Enum 的 toString()
表示.在数据库列仅由一个字符组成的场景中,这是一个问题.例如,我有以下枚举:
Hibernate provides @Enumerated
annotation which supports two types of Enum
mapping either using ORDINAL
or STRING
. When we map using EnumType.STRING
, it takes the "name" of the Enum
and not the toString()
representation of the Enum. This is a problem in scenarios where the database column consists of only one character. For example, I have the following Enum:
public enum Status{
OPEN{
@Override
public String toString(){
return "O";}
},
WAITLIST{
@Override
public String toString(){
return "W";}
},
COMPLETE{
@Override
public String toString(){
return "C";}
}
}
当我使用 @Enumerated(EnumType.STRING)
持久化枚举 Status.OPEN
时,Hibernate 尝试存储在数据库中的值是 OPEN.但是,我的数据库列仅包含一个字符,因此会引发异常.
When I persist the enum Status.OPEN
using @Enumerated(EnumType.STRING)
, the value that Hibernate tries to store in the database is OPEN. However, my database column consists of only one character and hence it throws an exception.
解决此问题的一种方法是更改 Enum 类型以保存单个字符(如 STATUS.O
、STATUS.W
而不是 STATUS.OPEN
, STATUS.WAITLIST
).但是,这会降低可读性.有什么建议可以保持可读性以及将 Enum 映射到单个字符列吗?
One way to overcome this issue is to change the Enum type to hold single characters (like STATUS.O
, STATUS.W
instead of STATUS.OPEN
, STATUS.WAITLIST
). However, this reduces readability. Any suggestions to preserve the readability as well as mapping the Enum to a single character column?
谢谢.
推荐答案
查看这两篇文章 - http://community.jboss.org/wiki/Java5EnumUserType 和 http://community.jboss.org/wiki/UserTypeforpersistingaTypesafeEnumerationwithaVARCHARcolumn
Check these two articles - http://community.jboss.org/wiki/Java5EnumUserType and http://community.jboss.org/wiki/UserTypeforpersistingaTypesafeEnumerationwithaVARCHARcolumn
他们通过自定义 UserType 解决问题.
They solve the problem by a custom UserType.
这篇关于休眠@Enumerated 映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!