我正在研究Hibernate,并且遇到了与Hibernate注释相关的非明确情况。
假设我们有两个实体:
主题和发言人
一个话题可能与许多发言者有关。一个主题可能有几个发言者。 一位发言者可以参加几个主题。
如下所示:
我的普通应用程序包含两个实体类:主题类和扬声器类
Topic类包含注释,通过TOPIC_SPEAKERS表声明与SPEAKERS的一对多关系。如果TOPIC_SPEAKERS表不存在,则会在运行时生成。
Topic.class(跳过不相关的代码)
@Entity
@Table(name="TOPICS")
public class Topic implements Serializable {
@Id
@GeneratedValue
private long topicId;
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "TOPIC_SPEAKERS",
joinColumns = {
@JoinColumn(name = "topicId")},
inverseJoinColumns = {
@JoinColumn(name = "speakerId")})
private List<Speaker> speakersList;
和扬声器类标题:
@Entity
@Table(name="SPEAKERS")
public class Speaker implements Serializable {
@Id
@GeneratedValue
private long speakerId;
private String speakerName;
我在SPEAKERS表中添加了两条记录,它看起来像是:
然后我参考第一位发言人(John Doe)向TOPICS表添加了一个主题。
TOPICS table:
and TOPIC_SPEAKERS table:
一切正常,直到我试图添加另一个话题,指的是第一个发言者(John Doe)。即,将第二个主题添加到TOPICS表中,将“TOPIC_SPEAKERS”中的“第二个主题”引用到第一个发言者(John Doe)。
产生的TOPIC_SPEAKERS应该是这样的(65536 - John Doe的id):
# TOPICID SPEAKERID
1 131072 65536
2 132111 65536
但是Hibernate不允许向具有重复SPEAKERID值的TOPIC_SPEAKERS插入记录。
我收到以下错误:
could not insert collection: [simpledbtest.model.Topic.speakersList#163840]
SEVERE: The statement was aborted because it would have caused a duplicate key value
in a unique or primary key constraint or unique index identified by 'SQL130314230217010'
defined on 'TOPIC_SPEAKERS'.
....
Caused by: java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because
it would have caused a duplicate key value in a unique or primary key constraint or unique
index identified by 'SQL130314230217010' defined on 'TOPIC_SPEAKERS'.
....
Caused by: org.apache.derby.client.am.SqlException: The statement was aborted because it
would have caused a duplicate key value in a unique or primary key constraint or unique index
identified by 'SQL130314230217010' defined on 'TOPIC_SPEAKERS'.
我的问题 - 如何更改Topic类中的注释以允许生成的TOPIC_SPEAKERS表中的重复列值?
谢谢。
答案 0 :(得分:1)
您正在描述ManyToMany关系,并且必须使用@ManyToMany注释。像这样:
@Entity
@Table(name="TOPICS")
public class Topic implements Serializable {
@Id
@GeneratedValue
private long topicId;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "TOPIC_SPEAKERS",
joinColumns = {
@JoinColumn(name = "topicId")},
inverseJoinColumns = {
@JoinColumn(name = "speakerId")})
private Set<Speaker> speakersList;
@Entity
@Table(name="SPEAKERS")
public class Speaker implements Serializable {
@Id
@GeneratedValue
private long speakerId;
@ManyToMany(mappedBy = "speakersList")
private Set<Topic> topics;
private String speakerName;