0

我正在研究 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 不允许向 TOPIC_SPEAKERS 插入一条具有重复 SPEAKERID 值的记录。

我收到以下错误:

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 表中的重复列值?

谢谢你。

4

1 回答 1

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;
于 2013-03-14T20:25:41.017 回答