开发者

JPA Shared Entity mapping

I have a scenario where I have a Object called Page, and another object called Tag, relationship between these two is Page has Tags(many to many), but the same Tags can also shared with Product, here also the relationship is same Product has Tags (many to many).

In normal scenario I will create a type column in Tag where type may be Enum value (product, page) and use query like SELECT * from T开发者_高级运维ags where parent_id = page_id and type = page.

How to do this in JPA (how to create this relationship and how to query data)


I think you should create two tables of associations. One to associate Pages with tags, one to associate Products with tags. The code:

@Entity
@Table(name = "page")
class Page {
  ....

    @OneToMany
    @JoinTable(name = "jnd_pages_tags", joinColumns = @JoinColumn(name = "page_fk"),
            inverseJoinColumns = @JoinColumn(name = "tag_fk"))
    private Set<Tag> tags;      
}

@Entity
@Table(name = "page")
class Product {
  ....

    @OneToMany
    @JoinTable(name = "jnd_products_tags", joinColumns = @JoinColumn(name = "products_fk"),
            inverseJoinColumns = @JoinColumn(name = "tag_fk"))
    private Set<Tag> tags;      
}

@Entity
@Table(name = "tags")
class Tag {
.....
}

to select corresponding tags for page, use

SELECT p.t FROM Page p WHERE p.id = :id

to select corresponding tags for product, use

SELECT p.t FROM Product p WHERE p.id = :id
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜