我可以使用 Hibernate Annotations 自动将 EnumSet 映射到一系列布尔列吗?

发布于 2024-07-14 12:29:38 字数 172 浏览 6 评论 0原文

我有一个 EnumSet,我认为将其映射到一系列布尔列会很好。 这将使使用 SQL 工具进行检查变得容易,并且还可以适应可用枚举值的更改。 然而,我真的不想为此手写所有的 getter 和 setter。

有谁有一个聪明的解决方案,使用某种休眠元数据将该对象拆分为一堆属性?

谢谢!

I have an EnumSet that I thought it would be good to map into a series of boolean columns. This will make it easy to inspect using SQL tools and also resilient to changes to the available enum values. However, I don't really want to hand-write all the getters and setters for this.

Does anyone have a clever solution using some kind of hibernate metadata to split this object into a bunch of properties?

Thanks!

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

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

发布评论

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

评论(1

长安忆 2024-07-21 12:29:38

如果我理解正确的话,对于这样的枚举:

public enum Color { RED, GREEN, BLUE; }

数据库中将有 3 个真/假列,每个列对应一个可能的枚举值。 然后,包含 RED 和 BLUE 的 EnumSet 应该映射到:

RED    GREEN    BLUE
true   false    true

如果是这种情况,我知道的唯一方法是编写您自己的 org.hibernate.usertype 实现。用户类型。 这是一项非常简单的任务,Hibernate 站点上提供了一些示例,例如 在这里

编辑:我刚刚意识到事情必须变得更加复杂。 如果您希望为应用程序中所有可能的 EnumSet 使用一个 Hibernate 类型映射,则必须执行以下操作:

  1. 使用 org.hibernate.usertype.ParameterizedType 并让 user可通过枚举类参数化的类型。
  2. 根据枚举类的值,确定要读/写的列数和列数。
  3. 每次使用 EnumSet 时实例化该类型。
  4. 考虑在一个表中映射多个集合的可能性,以及添加新的枚举值将如何影响现有类型的工作。

这很容易相当于一整天的工作,但似乎是完全可行的。 希望你能从这里弄清楚。

If I understand you correctly, for an enum like:

public enum Color { RED, GREEN, BLUE; }

you would have 3 true/false columns in a database, one for each possible enum value. Then an EnumSet containing, say, RED and BLUE, should be mapped to:

RED    GREEN    BLUE
true   false    true

If that's the case, the only way I know of is to write your own implementation of org.hibernate.usertype.UserType. It's a pretty straight-forward task, with some examples available on Hibernate site and, for instance, here.

Edit: I just realized things would have to be somewhat more complex. If you wish to have one Hibernate type mapping for all possible EnumSet in your application, you will have to do the following:

  1. Use org.hibernate.usertype.ParameterizedType and make user type parameterizable by an enum class.
  2. Depending on values of enum class, determine how many and what columns to read/write.
  3. Instantiate the type each time an EnumSet is used.
  4. Consider the possibility of mapping multiple sets in one table, as well as how adding a new enum value will influence workings of existing type.

This could easily amount to full day's work, but seems quite doable. Hope you figure it out from here.

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