Search code examples
javahibernatejpaannotations

Map a list of strings with JPA/Hibernate annotations


I want to do something like this:

    @Entity public class Bar {
        @Id @GeneratedValue long id;
        List<String> Foos
    }

and have the Foos persist in a table like this:

foo_bars (
    bar_id int, 
    foo varchar(64)
);

UPDATE:

I know how to map other entities, but it's overkill in many cases. It looks like what I'm suggesting isn't possible without creating yet another entity or ending up with everything in some blob column.


Solution

  • This is in Hibernate terms a "collection of values" or "elements". There is a (Hibernate specific) annotation for it. JPA does not support this (yet).

    In short, annotate your collection like this:

    @CollectionOfElements
    @JoinTable(
            table=@Table(name="..."),
            joinColumns = @JoinColumn(name="...") // References parent
    )
    @Column(name="...value...", nullable=false)
    

    This will create the necessary table with foreign keys and restrictions.