views:

3569

answers:

5

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.

A: 

create an entity 'FooBars'

refactor the attribut 'Foos' to

@OneToMany List Foos

Michael Lange
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
A: 

I'm think it's that what you need:

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

    @OneToMany(mappedBy="bar")   //"bar" = field name in mapping class
    List<FooBar> Foos;
}

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

    @ManyToOne
    @JoinColumn(name="bar_Id")  
    Bar bar;
}
Vanger
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.
danb
+5  A: 

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.

Maarten Winkels
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:http://en.wikibooks.org/wiki/Java_Persistence/ElementCollection
Tom Anderson
+1  A: 

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()]));
Renaud
A: 

I sometimes prefer persisting such collections as @Lobs (i.e. serializing them in the database)

Bozho
difficult to query effectively like that...
danb
Yes, if you will make queries, this is not an option.
Bozho