Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a Primary Key on @ElementCollection

So, there is that behavior with innodb that can cause problem if some tables lack of primary key.

So with Hibernate, I am looking for a key to specifies a primary key on a @ElementCollection table with a Set as the underling data structure.

I found a way to have a primary key with a map, but it is kind of weird because I do not need a map.

I also found an answer related to @Embeddable, but I do not need that kind of complexities. I am using a Set or Set as the data structure in my entities.

Any idea how to achieve that?

like image 336
plcstpierre Avatar asked May 05 '15 12:05

plcstpierre


2 Answers

If you use a Set and make the element Column be not null, then hibernate will make a primary key with the join column and element column.

Example:

@Column(name = "STRINGS", nullable = false)
@ElementCollection
private Set<String> strings;
like image 80
Dave L. Avatar answered Sep 18 '22 00:09

Dave L.


@ElementCollection cannot take a primary key, because an Embeddable types cannot have an identifier.

You can add an @OrderColumn to optimize the generates SQL statements.

If you need a primary key, then you should turn the @ElementCollection into a @OneToMany association.

like image 45
Vlad Mihalcea Avatar answered Sep 20 '22 00:09

Vlad Mihalcea