简体   繁体   English

JPA - 多对多作为 ElementCollection

[英]JPA - many-to-many as ElementCollection

I've got a many-to-many relationship that assigns labels (nothing but string) to items:我有一个多对多的关系,将标签(除了字符串)分配给项目:

+------+   +------------+   +-------+
| ITEM |   | ITEM_LABEL |   | LABEL |
|------|   |------------|   |-------|
|  ID  |<->|  ITEM_ID   | ┌>|  ID   |
|------|   |------------| | |-------|
| .... |   |  LABEL_ID  |<┘ | TEXT  |
+------+   +------------+   +-------+

... and I'd like to avoid creating POJO class for the label table and keep it in the Item class as a collection of strings. ...并且我想避免为 label 表创建 POJO class 并将其作为字符串集合保存在 Item class 中。 Is there a way to do it with JPA (hibernate) annotations?有没有办法用 JPA (休眠)注释来做到这一点?

I've tried to combine @CollectionTable with @JoinTable but it obviously does not work:我试图将@CollectionTable 与@JoinTable 结合起来,但它显然不起作用:

@Entity
public class Item {

    @Id
    private long id;

    @ElementCollection
    @JoinTable(name = "ITEM_LABEL", joinColumns = @JoinColumn(name = "ITEM_ID"))
    @CollectionTable(name = "LABEL", joinColumns = @JoinColumn(name = "ID", referencedColumnName = "LABEL_ID"))
    @Column(name = "TEXT")
    private Collection<Strings> labels;
}

Can anyone tell me how could I include the labels as a collection of string in the item class, please?谁能告诉我如何将标签作为字符串集合包含在项目 class 中,好吗? Many thanks!非常感谢!

@JoinTable is used to map following associations to database table: bidirectional many-to-one/one-to-many, unidirectional many-to-one, and one-to-one (both bidirectional and unidirectional) associations. @JoinTable用于 map 以下与数据库表的关联:双向多对一/一对多、单向多对一和一对一(双向和单向)关联。

If you really want to have Label with his own table you have to define it as an Entity and then using ManyToMany relation.如果你真的想要Label和他自己的表,你必须将它定义为一个Entity ,然后使用ManyToMany关系。

The other solution would be to remove Label table and keep label name as LABEL instead of label_id inside item_label table.另一种解决方案是删除Label表并将 label 名称保留为LABEL而不是item_label表中的 label_id。

So your relation will become所以你的关系会变成

@ElementCollection
@CollectionTable(name = "ITEM_LABEL", joinColumns = @JoinColumn(name = "ITEM_ID"))
@Column(name = "LABEL")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM