【问题标题】:Many-To-Many with attributes and composite id具有属性和复合 id 的多对多
【发布时间】:2013-03-05 17:06:04
【问题描述】:

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

这是我想要的:

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])

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

【问题讨论】:

  • 为什么“需要通知才能拥有复合键”?为什么不将Notification 更改为使用自动生成的UID,然后让Notification 中的2 个外键字段为非空列?此外,您在 Thread 中的多对多应使用“mappedBy”来提供集合。
  • 我认为答案与我为 [this question][1] 给出的答案相似。 [1]:stackoverflow.com/questions/18205248/…

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


【解决方案1】:

好吧,我第一次尝试答案显然太微不足道了!

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

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

【讨论】:

    猜你喜欢
    • 2014-12-07
    • 2020-03-04
    • 1970-01-01
    • 2016-05-26
    • 2022-01-22
    • 1970-01-01
    • 2019-04-08
    • 2014-03-12
    • 2013-02-08
    相关资源
    最近更新 更多