如何处理java枚举和数据库表之间的重复?

发布于 2024-07-16 11:25:30 字数 466 浏览 2 评论 0原文

在我们的应用程序中,某些实体必须由枚举表示是一种很常见的情况:例如类型、类别、状态等。

通常,代码中存在使用这些值来决定一个操作或另一个操作的条件或流程,因此这些值必须以某种方式为应用程序“已知”(即它必须能够引用特定实例)来决定而不是参考整个类)。 这就是为什么我们使用枚举而不只是常规类。

问题是这些实体还需要作为其他实体的字段存储(或至少引用)在数据库中。 我们通常为每个实体创建一个表,以便能够在这些列中进行引用完整性检查,并且数据单独在数据库中具有“含义”,而不需要引用枚举来找出每个 id 的含义。

理想情况下,这些实体的数据应从枚举中的数据填充,但现在我们在数据库初始化脚本中重复了这些值。

当使用像 Hibernate 这样的 ORM 时,事情会变得有点复杂。

我想知道其他人如何处理这种情况。

我对在枚举和数据库表之间进行重复的想法不太满意,但我还没有找到更好的解决方案。

It is a quite common situation in our applications that some entity have to be represented by an enum: for example types, categories, status, and things like that.

Often, there are conditions or flows in the code that use the values to decide between one action or another, so the values have to be "known" in some way for the application (i.e. it has to be able to refer to a specific instance to decide instead of referencing the class in a whole). That is why we use enums instead of just a regular class.

The problem is that these entities also need to be stored (or at least referenced) in the database, as fields of other entities. We usually create a table for each entity, to be capable of having referencial integrity checks in these columns, and also that the data have a "meaning" in the database alone without the need to refer to the enum to find out what each id means.

Ideally, the data for these entities should be populated from the data in the enum, but nowadays we have the values duplicated in the db initialization scripts.

It becomes a bit more complicated when an ORM like Hibernate is used.

I'd like to know how other people handles this kind of situation.

I'm not fully comfortable with the idea of having a duplication between an enum and a database table, but I haven't found a better solution yet.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

十雾 2024-07-23 11:25:30

尝试回答这个问题:在数据库中保存枚举的方法

Try the answers to this question: Ways to save enums in database

安静 2024-07-23 11:25:30

我的 JPA/Hibernate 应用程序也有同样的问题。 我所做的是在遇到枚举条目时在数据库中动态创建它们。 在这里,它会根据需要自动填充。

I have the same issue for my JPA/Hibernate app. What I do is dynamically create the enum entry in the database as they're encountered. In this was it auto-populates as needed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文