Search code examples
javahibernatejpaormmany-to-many

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. Is there a way to do it with JPA (hibernate) annotations?

I've tried to combine @CollectionTable with @JoinTable but it obviously does not work:

@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? Many thanks!


Solution

  • @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.

    If you really want to have Labelwith his own table you have to define it as an Entity and then using ManyToMany relation.

    The other solution would be to remove Label table and keep label name as LABEL instead of label_id inside item_label table.

    So your relation will become

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