Map a list of strings with JPA/Hibernate annotations

43,411

Solution 1

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.

Solution 2

Here is how you would do this if you are using JPA2:

@Entity public class Bar {
   @Id @GeneratedValue long id;

   @ElementCollection
   @CollectionTable(name="foo_bars", joinColumns=@JoinColumn(name="bar_id"))
   @Column(name="foo")
   List<String> Foos;
 }

For a clearer example see section 2.2.5.3.3 in the Hibernate Annotations Reference Guide.

Solution 3

If you store your list as an array, it works:

setFoos(String[] foos);

you can transform it like this:

setFoos(myList.toArray(new String[myList.size()]));
Share:
43,411
danb
Author by

danb

I try

Updated on September 10, 2020

Comments

  • danb
    danb over 3 years

    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.

  • danb
    danb about 15 years
    Thanks, Michael, but I was hoping to avoid another entity here.. I really only need the string in any case.. I was hoping to get hibernate to deal it all for me.
  • danb
    danb about 15 years
    thanks Vanger, but I was hoping to avoid another entity here.. I really only need the string in any case.. I was hoping to get hibernate to deal it all for me.
  • Tom Anderson
    Tom Anderson about 14 years
    As of JPA 2, you can do this portably with the ElementCollection annotation, which is basically a standardised version of CollectionOfElements, and lets you have collections of Embeddables or basic types, which includes strings: en.wikibooks.org/wiki/Java_Persistence/ElementCollection