在数据库中保存枚举的方法 [英] Ways to save enums in database

查看:245
本文介绍了在数据库中保存枚举的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道将枚举保存到数据库的最佳方法是什么。

I am wondering what the best ways to save enums into a database is.

我知道有 name() valueOf()方法将其转换为String。但是有没有其他(灵活的)选项来存储这些值?

I know there are name() and valueOf() methods to make it into a String back. But are there any other (flexible) options to store these values?

有一个聪明的方式使它们成为唯一的数字( ordinal

Is there a smart way to make them into unique numbers (ordinal() is not safe to use)?

任何意见和建议都会有所帮助:)

Any comments and suggestions would be helpful :)

更新:

感谢所有真棒和快速的答案!这是我怀疑的。

Thanks for all awesome and fast answers! It was as I suspected.

但是,工具包的注释;这是一种方式。问题是,我将不得不添加相同的方法与我创建的每个枚举类型。这是很多重复的代码,目前,Java不支持任何解决方案(你不能让枚举扩展其他类)。

However a note to 'toolkit'; That is one way. The problem is that I would have to add the same methods with each enum type i create. Thats a lot of duplicated code and, at the moment, Java does not support any solutions to this (You cannot let enum extend other classes).

但是,感谢所有答案!

推荐答案

我们永远不会将枚举存储为数字序数值;它使调试和支持的方式太难了。我们将实际枚举值存储到字符串中:

We never store enumerations as numerical ordinal values anymore; it makes debugging and support way too difficult. We store the actual enumeration value converted to string:

public enum Suit { Spade, Heart, Diamond, Club }

Suit theSuit = Suit.Heart;

szQuery = "INSERT INTO Customers (Name, Suit) " +
          "VALUES ('Ian Boyd', %s)".format(theSuit.name());

,然后读回:

Suit theSuit = Suit.valueOf(reader["Suit"]);

问题是过去盯着企业管理器,试图破译:

The problem was in the past staring at Enterprise Manager and trying to decipher:

Name                Suit
==================  ==========
Shelby Jackson      2
Ian Boyd            1

诗歌

Name                Suit
==================  ==========
Shelby Jackson      Diamond
Ian Boyd            Heart

更容易。前者需要获取源代码并查找分配给枚举成员的数值。

the latter is much easier. The former required getting at the source code and finding the numerical values that were assigned to the enumeration members.

是需要更多空间,但枚举成员名称很短,和硬盘驱动器是便宜的,它是更值得帮助,当你有一个问题。

Yes it takes more space, but the enumeration member names are short, and hard drives are cheap, and it is much more worth it to help when you're having a problem.

此外,如果你使用数值,你绑定他们。你不能很好地插入或重新排列成员,而不必强制使用旧的数值。例如,将Suit枚举更改为:

Additionally, if you use numerical values, you are tied to them. You cannot nicely insert or rearrange the members without having to force the old numerical values. For example, changing the Suit enumeration to:

public enum Suit { Unknown, Heart, Club, Diamond, Spade }

必须成为:

public enum Suit { 
      Unknown = 4,
      Heart = 1,
      Club = 3,
      Diamond = 2,
      Spade = 0 }

,以维护存储在数据库中的旧数值。

in order to maintain the legacy numerical values stored in the database.

这篇关于在数据库中保存枚举的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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