与Java中枚举类型的关系

发布于 2024-08-13 04:19:10 字数 399 浏览 4 评论 0原文

我正在尝试在两种类型之间创建多对多关系,其中一种是枚举类型。假设第一个模型是用户,第二个模型是角色。一个用户可以有多个角色,一个角色可以属于多个用户。

我希望能够编写简单的代码,例如:

if (user.getRoles().contains(Role.ADMIN)) {
  //do something
}

有谁知道这是否可能?我已经看到有一个 @Enumerated Hibernate 注释,但这看起来对我没有用。

我目前已经通过为链接表创建模型来实现解决方案,但这非常混乱。非常感谢任何帮助。

-gearoid

更新: 有人可以指定如何在模型上保留 EnumSet 吗?上面的信息仍然有效,我希望使用枚举类型创建多对多关系。

I'm trying to create a many-to-many relationship between two types of which one is an Enumerated type. Lets say the first model is User and the second model is Role. A user can have many roles and a role can belong to many users.

I'd like to be able to write simple code like:

if (user.getRoles().contains(Role.ADMIN)) {
  //do something
}

Does anyone know if this is possible? I've seen that there is an @Enumerated Hibernate annotation but this doesn't look to be of use to me.

I've currently implemented a solution by created a model for a link table but this is very messy. Any help much appreciated.

-gearoid

UPDATE: Can someone specify how to persist an EnumSet on a model? The info above still stands, I wish to create a ManyToMany relationship with an Enumerated Type.

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

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

发布评论

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

评论(3

病女 2024-08-20 04:19:10

您是否看过 EnumSet班级?这可以在集合中存储多个 Enum 实例,您可以对其调用 contains()

Have you had a look at the EnumSet class? This can store multiple Enum instances in a collection you can call contains() on

七分※倦醒 2024-08-20 04:19:10

我想我已经找到了解决问题的好方法。如果我将枚举类型保持为简单的类型,例如:

public enum Role implements Serializable{

    USER, MODERATOR, ADMIN;

}

然后在我的用户模型上,我使用 @CollectionOfElements 创建一组角色,所以它看起来像这样:

  @CollectionOfElements(fetch = FetchType.EAGER)
  public Set<Role> getRoles() {
      return roles;
  }

  public void setRoles(Set<Role> roles) {
      this.roles = roles;
  }

Hibernate 似乎为这种关系创建了一个表(称为 user_roles),它可以工作如我所愿(常规的多对多关系)。

希望这对某人有帮助。

-齿轮。

I think I have found a good solution to the problem. If I keep my Enumerated Type as something simple such as:

public enum Role implements Serializable{

    USER, MODERATOR, ADMIN;

}

And then on my User model I create a Set of Roles with the @CollectionOfElements so it looks something like this:

  @CollectionOfElements(fetch = FetchType.EAGER)
  public Set<Role> getRoles() {
      return roles;
  }

  public void setRoles(Set<Role> roles) {
      this.roles = roles;
  }

Hibernate seems to create a table for this relationship (called user_roles) which works as I'd like (A regular manyToMany relationship).

Hope this helps someone.

-gearoid.

追我者格杀勿论 2024-08-20 04:19:10

我们通常创建子类EnumUserType,然后在映射文件中指定该类。

We usually create subclasses EnumUserType and then specify this class in the mapping file.

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