本文介绍了使用和持久化枚举的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这里讨论了关于处理和保持枚举类值的最佳方式的几个问题/讨论(例如,),而且我想问一般的consenus是什么。

I've seen several questions/discussions here about the best way to handle and persist enum-like values (e.g. Persisting data suited for enums , How to persist an enum using NHibernate ), and I'd like to ask what the general consenus is.

特别是:


  • 这些值应该如何在代码中处理?

  • 如何将它们持久化到数据库(如文本/数字)?

  • 不同解决方案的折衷是什么?

注意:这个问题最初包含在这个答案中的解释。

推荐答案

我试图总结我的理解。如果您有任何更正,请随时编辑。所以在这里:

在代码

应该使用语言的本机枚举类型(至少在Java和C#中)或使用类似于。不要使用简单的常量(整数或类似的),因为您输入类型安全(并且很难理解哪些值是法律输入,例如方法)。

In the code, enums should be handled using either the language's native enum type (at least in Java and C#), or using something like the "typesafe enum pattern". Using plain constants (Integer or similar) is discouraged, as you lose type safety (and make it hard to understand which values are legal input for e.g. a method).

这两者之间的选择取决于枚举附加的附加功能:

The choice between these two depends on how much additional functionality is to be attached to the enum:


  • 如果要将功能的负载放入枚举(这是好的,因为你一直避免switch()),一个类通常更合适。

  • 另一方面,对于简单的枚举类值,语言的枚举通常更清晰。

特别是,至少在Java中,枚举不能从另一个类继承,所以如果你有几个枚举类似的行为,你想放入一个超类,你不能使用Java的枚举。

In particular, at least in Java an enum cannot inherit from another class, so if you have several enums with similar behavior which you'd like to put into a superclass, you cannot use Java's enums.

持久枚举

为了保持枚举,每个枚举值都应该被分配一个唯一的ID。这可以是整数或短字符串。一个简短的字符串是首选的,因为它可以是助记符(使数据库管理员等等更容易了解数据库中的原始数据)。

To persist enums, each enum value should be assigned a unique ID. This can be either an integer, or a short string. A short string is preferred, since it can be mnemonic (makes it easier for DBAs etc. to understand the raw data in the db).


  • 在软件中,每个枚举应该具有映射函数,用于在枚举之间转换(用于软件内部)和ID值(持续存在)。一些框架(例如(N)Hibernate)自动执行此操作有限。否则,您必须将其放入枚举类型/类中。

  • 数据库应该(理想情况下)包含列出合法值的每个枚举的表。一列是ID(见上文),这是PK。附加列可能对于例如说明。所有将包含该枚举值的表列可以使用这个枚举表作为FK。这样可以确保枚举值不能永久保持不变,并允许数据库独立。

方法是合法枚举值列表存在于两个位置(代码和数据库)。这是很难避免的,因此经常被认为是可接受的,但有两种选择:

One problem with this approach is that the list of legal enum values exists in two places (code and database). This is hard to avoid and therefore often considered acceptable, but there are two alternatives:


  • 只保留数据库中的值列表,生成在构建时的枚举类型。优雅,但意味着建立运行需要一个数据库连接,这似乎是有问题的。

  • 定义代码中值的列表是权威的。在运行时(通常在启动时)检查DB中的值,抱怨/中止不匹配。

这篇关于使用和持久化枚举的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:00