开发者

JPA Shared Entity mapping

开发者 https://www.devze.com 2023-03-25 08:01 出处:网络
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

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

精彩评论

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