具有属性和复合ID的多对多

时间:2013-03-05 17:06:04

标签: java hibernate jpa many-to-many composite-primary-key

假设我与属性有多对多的关系。我想用两个一对多关系代替它。如果我配置密钥,我会收到一个奇怪的警告,即主键的属性数量无效。

这是我想要的:

User <1:N> Notification <N:1> Thread

您应该注意,我需要通知一个由user_idthread_id组成的复合键。

这就是我尝试过的:

@Entity
public class Notification implements Serializable {

    @EmbeddedId
    @AttributeOverrides( {
        @AttributeOverride(name = "user_id", column = @Column(nullable = false)),
        @AttributeOverride(name = "thread_id", column = @Column(nullable =false))
    })
    private NotificationPK id;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "user_id", insertable = false, updatable = false)
    private User user;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "thread_id", insertable = false, updatable = false)
    private Thread thread;    
}   

在Thread类中,它看起来像这样:

    @OneToMany(fetch=FetchType.LAZY)
    @JoinTable(
        name="notifications",
        joinColumns=@JoinColumn(name="thread_id")
    )
    private Set<Notification> notifications = new HashSet<Notification>();

使用NotificationPK如下:

@Embeddable
public class NotificationPK implements Serializable {

    Long user_id;
    Long thread_id;
}

但是,一旦启动,我就会遇到以下异常:

 Caused by: org.hibernate.MappingException: 
     Foreign key (FK4BD694E87364C017:notifications 
        [notifications_thread_id,notifications_user_id])) 
     must have same number of columns as the referenced 
     primary key (notifications 
        [thread_id,notifications_thread_id,notifications_user_id])

我做错了什么?为什么他希望这是主键的一部分?

1 个答案:

答案 0 :(得分:0)

好的,我第一次尝试答案的时候太过琐碎了!

您需要的是Notification的UID主键,它与构成“加入”的外键无关。

有关更具体的例子,请参阅我对this question的回答。