与Java中枚举类型的关系
我正在尝试在两种类型之间创建多对多关系,其中一种是枚举类型。假设第一个模型是用户,第二个模型是角色。一个用户可以有多个角色,一个角色可以属于多个用户。
我希望能够编写简单的代码,例如:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否看过 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我想我已经找到了解决问题的好方法。如果我将枚举类型保持为简单的类型,例如:
然后在我的用户模型上,我使用 @CollectionOfElements 创建一组角色,所以它看起来像这样:
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:
And then on my User model I create a Set of Roles with the @CollectionOfElements so it looks something like this:
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.
我们通常创建子类EnumUserType,然后在映射文件中指定该类。
We usually create subclasses EnumUserType and then specify this class in the mapping file.