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
);
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.
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.
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.
@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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With