Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate 4 @OneToMany List<String>

For a @OneToMany relationship do I have to map to Objects ?

I have the following example

@Entity
@Table(name="FOO_TABLE")
public class Foo {

    @Id
    @Column(name="ID")
    @GeneratedValue
    private int id;

    ?????
    private List<String> bars;

}

If bars were an object i would do

@ManyToOne
@JoinColumn(name="ID_FOO")

and the problem would be solved. However, I want avoid to create an object to only represent a pair of strings (reference key, value).

FOO and BAR are stored in separate tables

CREATE TABLE Foo (
    ID INTEGER NOT NULL AUTO_INCREMENT,
    //SOME OTHER PROPERTIES
    PRIMARY KEY( ID),
);

CREATE TABLE Bar (
    ID_FOO INTEGER,
    VAL VARCHAR(256),
    PRIMARY KEY (ID_FOO, VAL),
    FOREIGN KEY ( ID_FOO) REFERENCES Foo( ID) ON DELETE CASCADE
);
like image 856
fxe Avatar asked Nov 13 '13 23:11

fxe


People also ask

How do you persist a string list?

You just need to annotate the attribute with @ElementCollection and the persistence provider will persist the elements of the Collection in an additional database table.

How do you map one to many?

One To Many Mapping in Hibernate. In simple terms, one to many mapping means that one row in a table can be mapped to multiple rows in another table. For example, think of a Cart system where we have another table for Items. A cart can have multiple items, so here we have one to many mapping.

What is the difference between mappedBy and @JoinColumn?

The @JoinColumn annotation helps us specify the column we'll use for joining an entity association or element collection. On the other hand, the mappedBy attribute is used to define the referencing side (non-owning side) of the relationship.


1 Answers

@ElementCollection is what you are looking for. This lets you define a mapping for a non-Entity class e.g. Embeddable or Basic.

http://en.wikibooks.org/wiki/Java_Persistence/ElementCollection

You can also use @CollectionTable to define the table.

@ElementCollection
@CollectionTable(name = "data" ....)
private List<String> data;
like image 180
Alan Hay Avatar answered Oct 02 '22 15:10

Alan Hay