One to many mapping with many possibilities

北城余情 提交于 2020-01-06 13:07:25

问题


I'm trying to persist my data but am having trouble coming up with a schema that will work for hibernate in a sane way

I have two objects: a channel and user. The user is associated with the channel but in many ways. It can have 5 special statuses (and can be assigned multiple ones) or be normal. The issue is complicated by the fact that its a many to many relationship (a user can be in multiple channels and a channel has multiple users).

My idea is to have separate channel and user tables but have a third big map table. This big map table would look something like this

--------------------------------------------------------------------------
| CHANNEL_ID | USER_ID | STATUS1 | STATUS2 | STATUS3 | STATUS4 | STATUS5 |
--------------------------------------------------------------------------
|      5     |    10   |    0    |    1    |    0    |     0   |    0    |
--------------------------------------------------------------------------

Note that if a new user joins a channel, they get a new row. However if they get a new status, their existing row is changed.

Whats really confusing me is how to implement something like that in Hibernate. I've got something like this but I've been playing around with this so long (2 days now) I don't even know what it does anymore.

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "quackbot_user_map", joinColumns = {
    @JoinColumn(name = "USER_ID")}, inverseJoinColumns = {
    @JoinColumn(name = "STATUS1")}) 
protected Set<UserDAOHb> status1s;
  • Is there a better way to do this?
  • Should I use a dedicated map object that represents the table and query with that instead?

回答1:


If you want to map that design, you need a third entity, that I'll call Participation.

  • One user has many participations;
  • One channel has many participations;
  • One participation has one channel, one user, and 5 boolean fields (status1 to status5)

But a more normal (and certainly easier to query) way of designing this would be to have a Participation entity with just one status, and create a Participation instance per User-Channel-Status tuple. If you think about it, it would be the only possible mapping (as far as I see) if the number of possible statuses was much bigger (or not fixed at all).



来源:https://stackoverflow.com/questions/6629668/one-to-many-mapping-with-many-possibilities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!