将额外的属性添加到休眠JoinTable [英] Adding additional Property to hibernate JoinTable
问题描述
我有两个实体,消息和用户。用户与消息具有ManyToMany关系(用户可以有很多消息),消息(现在为了减少复杂性)与用户具有ManyToMany关系(消息可以发送给多个用户)。
我使用@JoinTable连接两个实体,但是,我想向连接表添加一个状态列,以确定该消息是否是新的,读取等我在考虑将该列放入Message实体中,但是,我认为这可能是不可能的。
我已经看到很多关于使用中介实体的问题的答案,但我希望尽可能避免这种情况。
有没有人有任何可能的解决方案来解决我的问题?
JPA 2.0(即Hibernate 3.5及更高版本)引入了对建立三元关系的支持,如 Map
s。例如,你可以做这样的事情(尽管如果你需要双向关系,我不知道如何处理另一方):
public enum MessageStatus {READ,UNREAD}
public class User {
...
@ElementCollection
@CollectionTable(name =MessagesToUsers,joinColumns = @JoinColumn(name =userId))
@Column(name =messageStatus)
@MapKeyJoinColumn(name =messageId)
private Map< Message,MessageStatus> messages = new HashMap< Message,MessageStatus>();
...
}
I have two entities, Message and User. User has a ManyToMany relationship to Message (A user can have many messages) and Message (for now, to make it less complex) has a ManyToMany relationship to User (a message can be sent to multiple users).
I am joining the two entities using @JoinTable, however, I would like to add a "status" column to the join table to tell if the message is new, read, etc. I was thinking of putting the column in the Message entity, however, I'm thinking this is probably not possible.
I've seen a lot of answers to this question saying to use an intermediary entity, but I would like to avoid that if possible.
Does anyone have any possible solution to my problem?
JPA 2.0 (i.e. Hibernate 3.5 and above) introduced a support for modeling ternary relationships as Map
s. For example, you can do something like this (though I'm not sure what to do with the other side if you need a bidirectional relationship):
public enum MessageStatus { READ, UNREAD }
public class User {
...
@ElementCollection
@CollectionTable(name = "MessagesToUsers", joinColumns = @JoinColumn(name = "userId"))
@Column(name = "messageStatus")
@MapKeyJoinColumn(name = "messageId")
private Map<Message, MessageStatus> messages = new HashMap<Message, MessageStatus>();
...
}
这篇关于将额外的属性添加到休眠JoinTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!