【问题标题】:Java-EE-6: How to store a boolean in a @ManyToMany and @ManyToOne relationships?Java-EE-6:如何在 @ManyToMany 和 @ManyToOne 关系中存储布尔值?
【发布时间】:2013-02-26 17:40:35
【问题描述】:

我正在研究一个基本上由用户和文档组成的数据模型。现在每次添加新文档时,只要特定用户没有查看它(例如点击它),就应该有一个将文档标识为“未见过”的标志。

您将如何为这样的场景建模?有没有办法将布尔值/标志附加到用户和文档之间的关系?

这是我的简化模型:

@Entity
@Table(name="User")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    @Column(length = 128)
    private String name;
    @ManyToMany(mappedBy = "users", fetch=FetchType.LAZY)
    private List<Document> documents = new ArrayList<Document>();

    // getters and setters ...

}

这是文档类:

@Entity
@Table(name = "Document")
public class Document {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    @ManyToMany(fetch=FetchType.LAZY)
    @JoinTable(name = "Inbox", joinColumns = @JoinColumn(name = "document_id"), inverseJoinColumns = @JoinColumn(name = "user_id"))
    protected List<User> users = new ArrayList<User>();

    // getters and setters ...

}

非常感谢您的帮助!

【问题讨论】:

  • 您似乎需要在您的连接表中增加一列,查看。因此,您需要将多对多拆分为两个一对多/多对一关系。
  • 感谢您的快速答复!我会尝试您的建议并尽快回来。

标签: java jakarta-ee jpa relationship relation


【解决方案1】:

在 JB Nizet 的回答中,Matt 提到的连接表有一个唯一的主键 (id)、一个对两个外键的唯一约束和一个附加列。这是一个不错的选择。

但是当您使用@ManyToMany 时,您很可能在连接表中有一个由两个外键组成的主键。如果您想保留该模式并添加一个额外的viewed 列,您很可能需要习惯使用@Embeddable 类以使复合主键反映在您的@Entity 中。请记住,当您这样做时,您需要覆盖equals/hashcode

您可以将my answer on the other question 作为创建@Entity 类的起点。答案中描述了连接表中的实体及其主键。

【讨论】:

    【解决方案2】:

    向您的Inbox 连接表添加一个新列,以存储“未见”布尔值。然后map the join table as new entity, and decompose the many-to-many association into two OneToMany associations

    【讨论】:

      猜你喜欢
      • 2013-04-23
      • 2019-05-23
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 2012-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多