适合枚举的持久化数据 [英] Persisting data suited for enums

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

问题描述

大多数项目都有某种类型的数据,这些数据在发布之间基本上是静态的,非常适合用作枚举,例如状态、事务类型、错误代码等.例如,我将只使用通用状态枚举:

Most projects have some sort of data that are essentially static between releases and well-suited for use as an enum, like statuses, transaction types, error codes, etc. For example's sake, I'll just use a common status enum:

public enum Status {
    ACTIVE(10, "Active");
    EXPIRED(11, "Expired");
    /* other statuses... */

    /* constructors, getters, etc. */
}

我想知道其他人在处理此类数据的持久性方面做了什么.我看到了几个选项,每个选项都有一些明显的优点和缺点:

I'd like to know what others do in terms of persistence regarding data like these. I see a few options, each of which have some obvious advantages and disadvantages:

  • 将可能的状态保留在状态表中,并缓存所有可能的状态域对象以供整个应用程序使用
  • 只使用枚举,不保留可用状态列表,在我和我的 DBA 之间造成数据一致性的圣战
  • 在代码中保留状态并维护一个枚举,但不要将它们捆绑在一起,从而产生重复数据

我的偏好是第二个选项,尽管我的 DBA 声称我们的最终用户可能希望访问原始数据以生成报告,而不保留状态会导致数据模型不完整(反驳:这可以解决与文档).

My preference is the second option, although my DBA claims that our end users might want to access the raw data to generate reports, and not persisting the statuses would lead to an incomplete data model (counter-argument: this could be solved with documentation).

这里有大多数人使用的约定吗?人们对每个人的体验如何?还有其他选择吗?

Is there a convention that most people use here? What are peoples' experiences with each and are there other alternatives?

考虑了一段时间后,我真正的持久性斗争来自处理与数据库中的状态相关联的 id 值.安装应用程序时,这些值将作为默认数据插入.此时,它们的 ID 可用作其他表中的外键.我觉得我的代码需要知道这些 id,以便我可以轻松检索状态对象并将它们分配给其他对象.我该怎么办?我可以添加另一个字段,例如代码",以查找内容,或者仅按名称查找状态,这很麻烦.

After thinking about it for a while, my real persistence struggle comes with handling the id values that are tied to the statuses in the database. These values would be inserted as default data when installing the application. At this point they'd have ids that are usable as foreign keys in other tables. I feel like my code needs to know about these ids so that I can easily retrieve the status objects and assign them to other objects. What do I do about this? I could add another field, like "code", to look stuff up by, or just look up statuses by name, which is icky.

推荐答案

我们使用数据库中的一些显式字符串或字符值来存储枚举值.然后从数据库值返回到枚举,我们在枚举类上编写一个静态方法来迭代并找到正确的方法.

We store enum values using some explicit string or character value in the database. Then to go from database value back to enum we write a static method on the enum class to iterate and find the right one.

如果您期望有很多枚举值,您可以创建一个静态映射 HashMap 来快速翻译.

If you expect a lot of enum values, you could create a static mapping HashMap<String,MyEnum> to translate quickly.

不要存储实际的枚举名称(即示例中的ACTIVE"),因为这很容易被开发人员重构.

Don't store the actual enum name (i.e. "ACTIVE" in your example) because that's easily refactored by developers.

这篇关于适合枚举的持久化数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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