Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What column type is required when using ElementCollection with jpa?

I have a simple class with a column that is technically a List

@Entity
@Table(name='hat')
class Hat {
    @Id
    String id = UUID.randomUUID()

    @ElementCollection
    List<String> wat
}

Right now when I use either a varchar(500) or character varying(500) the PSQL code that pulls this entity out of the database explodes

org.postgresql.util.PSQLException: ERROR: relation "hat_wat" does not exist

like image 680
Toran Billups Avatar asked Aug 31 '25 22:08

Toran Billups


1 Answers

An element collection is not stored in a single column. It's stored in a separate table, just as if you have a OneToMany, except there is no identifier for the many side. Suppose the Hat foo has 2 wats "bar" and "baz":

hat table:             hat_wat table:

id                     hat_id    wat
-----                  ---------------
foo                    foo       bar
                       foo       baz

That allows querying the hats to find, for example, all the hats having "bar" in their list of wats. Trying to store multiple string in a single column is really not a good idea. It violates the first normal form rules.

like image 177
JB Nizet Avatar answered Sep 04 '25 16:09

JB Nizet