JPA:具有多个mappedBy属性的OneToMany关系

时间:2016-12-30 20:24:34

标签: java jpa persistence one-to-many entity-relationship

我在映射单个实体的实例之间的关系时遇到问题。让我先给你JPA实体。

文章实体

@Entity
@Table(name = "article")
public class Article {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "article", orphanRemoval = true)
    private Collection<Keyword> keywords;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "article1", orphanRemoval = true)
    private Collection<RelatedArticles> relatedArticles;

    @Column(name = "content", nullable = false)
    @Lob
    private String content;

    ...
}

RelatedArticle entity

@Entity
@Table(name = "related_articles")
public class RelatedArticles {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @JoinColumn(name = "article1_id")
    @ManyToOne(optional = false)
    private Article article1;

    @JoinColumn(name = "article2_id")
    @ManyToOne(optional = false)
    private Article article2;

    private Float weightedJaccardIndex;

    ...
}

进一步说明

文章可以与RelatedArticle实体实现的其他文章相关。该文章可由article1article2引用。这意味着relatedArticles中的集合Article应包含RelatedArticle的所有实例,其中ID与article1article2匹配。

问题

如何在我的Article实体中映射单个的RelatedArticle集合,其中原点Article是article1还是article2? 欢迎替代解决方案!

0 个答案:

没有答案