Reputation: 969
I have an entity A that contains a set of tags as in the following snippet:
@Entity
@Table(name = "tab_a")
public class A {
......
@Column(name = "name")
@ElementCollection(targetClass = Genre.class, fetch = FetchType.EAGER)
@CollectionTable(name = "tab_resource_tags", joinColumns = @JoinColumn(name = "id"))
@Enumerated(value = EnumType.STRING)
@OrderColumn
private Set<Genre> resourceTags;
------
}
I created an aditional tab_resource_tags just to have this thing working but when I run my unit tests and insert tags into the class A, the newly created table remains empty. I don't really see its point.
I was aiming for storing the tags in the same table where "A" entities are stored. Ideally they should be in plain text and separated by comma to be human readable.
My question is: Is it worth it to create a separate table only for inserting an set/list of enums? Wouldn't be more elegant to not reflect at all the enum into the database and have it inserted into the original "A" table?
Any opinions related to this would be highly appreciated.
Later edit:
As an workaround I tried specifying
@CollectionTable(name = "tab_a", joinColumns = @JoinColumn(name = "id"))
but Hibernate says that the columns from tab_a don't have default values (which is very weird, I'd say).
Upvotes: 0
Views: 1535
Reputation: 969
Here's how I solved this (in case anyone else needs this info):
The annotations are pretty much the same so you can take a look at the original question (the @Column for tags represents the column from the tab_resource_tags, not tab_a and @JoinColumn belongs to the same tab_resource_tags). A closer look for this can be taken here: http://en.wikibooks.org/wiki/Java_Persistence/ElementCollection
The issue was with the DB tables:
There's nothing special about tab_a's table in the DB. The important part is tab_resource_tags:
CREATE TABLE `tab_resource_tags` (
`resource_descriptor_id` int(11) NOT NULL,
`tag_name` varchar(255) NOT NULL
)
So now, each time I add an entity that contains a set of Enums of type Genre, they go into the tags table, effectively simulating a many-to-many relationship (only with Enums and not real classes).
Hope this makes it clear.
Upvotes: 1