Difference between @OneToMany and @ElementCollection?

前端 未结 6 1421
不思量自难忘°
不思量自难忘° 2020-11-28 02:19

What is the difference between using a @OneToMany and @ElementCollection annotation since both work on the one-to-many relationship?

相关标签:
6条回答
  • 2020-11-28 02:58

    Basic or Embedded: @ElementCollection
    Entities: @OneToMany or @ManyToMany

    @ElementCollection:

    • the relation is managed (only) by the entity in which the relation is defined
    • table contains id reference to the owning entity plus basic or embedded attributes

    @OneToMany / @ManyToMany:

    • can also be managed by the other entity
    • join table or column(s) typically contains id references only
    0 讨论(0)
  • 2020-11-28 03:03

    @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 Strings, 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.

    See also:

    • Java Persistence/ElementCollection
    0 讨论(0)
  • 2020-11-28 03:06

    ElementCollection can override the mappings, or table for their collection, so you can have multiple entities reference the same Embeddable class, but have each store their dependent objects in a separate table.

    0 讨论(0)
  • 2020-11-28 03:10

    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.

    0 讨论(0)
  • 2020-11-28 03:10

    @ElementCollection marks a collection. This does not necessarily mean that this collection references a 1-n join.

    0 讨论(0)
  • 2020-11-28 03:16

    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.

    0 讨论(0)
提交回复
热议问题