Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

java - 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
);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

@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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...