Hibernate @Enumerated映射 [英] Hibernate @Enumerated mapping

查看:113
本文介绍了Hibernate @Enumerated映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hibernate提供 @Enumerated 注释,它支持两种类型的枚举映射,使用 ORDINAL STRING 。当我们使用 EnumType.STRING 映射时,它需要枚举的名称,而不是 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";}
   }

}

当我坚持枚举 Status.OPEN 使用 @Enumerated(EnumType.STRING),Hibernate尝试存储在数据库中的值是打开。但是,我的数据库列仅包含一个字符,因此它会引发异常。

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.

克服此问题的一种方法是将枚举类型更改为保存单个字符(例如 STATUS.O STATUS.W 而不是 STATUS.OPEN STATUS.WAITLIST )。然而,这降低了可读性。任何建议保留可读性以及将枚举映射到单个字符列?

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.

这篇关于Hibernate @Enumerated映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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