Difference between @OneToMany and @ElementCollection?

前端 未结 6 1449
不思量自难忘°
不思量自难忘° 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 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 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.

    See also:

    • Java Persistence/ElementCollection

提交回复
热议问题