What is the difference between using a @OneToMany
and @ElementCollection
annotation since both work on the one-to-many relationship?
@ElementCollection
allows you to simplify code when you want to implement one-to-many relationship with simple or embedded type. For instance in JPA 1.0 when you wanted to have a one-to-many relationship to a list of String
s, you had to create a simple entity POJO (StringWrapper
) containing only primary key and the String
in question:
@OneToMany
private Collection strings;
//...
public class StringWrapper {
@Id
private int id;
private String string;
}
With JPA 2.0 you can simply write:
@ElementCollection
private Collection strings;
Simpler, isn't it? Note that you can still control the table and column names using @CollectionTable
annotation.