Annotation Type ElementCollection. @Target(value={METHOD,FIELD}) @Retention(value=RUNTIME) public @interface ElementCollection. Defines a collection of instances of a basic type or embeddable class. Must be specified if the collection is to be mapped by means of a collection table.
A OneToMany relationship in Java is where the source object has an attribute that stores a collection of target objects and if those target objects had the inverse relationship back to the source object it would be a ManyToOne relationship.
User Entity The configuration for this table is specified using the @CollectionTable annotation. The @CollectionTable annotation is used to specify the name of the table that stores all the records of the collection, and the JoinColumn that refers to the primary table.
Embeddable classes are used to represent the state of an entity but don't have a persistent identity of their own, unlike entity classes. Instances of an embeddable class share the identity of the entity that owns it. Embeddable classes exist only as the state of another entity.
ElementCollection
is a standard JPA annotation, which is now preferred over the proprietary Hibernate annotation CollectionOfElements
.
It means that the collection is not a collection of entities, but a collection of simple types (Strings, etc.) or a collection of embeddable elements (class annotated with @Embeddable
).
It also means that the elements are completely owned by the containing entities: they're modified when the entity is modified, deleted when the entity is deleted, etc. They can't have their own lifecycle.
I believe @ElementCollection
is mainly for mapping non-entities (embeddable or basic) while @OneToMany
is used to map entities. So which one to use depend on what you want to achieve.
@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<StringWrapper> strings;
//...
public class StringWrapper {
@Id
private int id;
private String string;
}
With JPA 2.0 you can simply write:
@ElementCollection
private Collection<String> strings;
Simpler, isn't it? Note that you can still control the table and column names using @CollectionTable
annotation.
Basic or Embedded: @ElementCollection
Entities: @OneToMany or @ManyToMany
@ElementCollection:
@OneToMany / @ManyToMany:
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