This article from the 《 Master JPA And Hibernate:Java Object Persistence technology details 》, Published by Tsinghua University Press , By sun Weiqin

Assume Customer Object's images Duplicate photo file names are not allowed in the collection , So we can images Property is defined as Set type :

private Set<String> images=new HashSet<String>();

In the database, a IMAGES surface , its CUSTOMER_ID Field as reference CUSTOMERS Table foreign key , because Customer Object does not allow duplicate photo file names , So we should put IMAGES Tabular CUSTOMER_ID and FILENAME Field as union primary key .
 Insert picture description here

Here are IMAGES Tabular DDL Definition :

create table IMAGES(
   CUSTOMER_ID bigint not null,
   FILENAME varchar(15) not null,
   primary key (CUSTOMER_ID,FILENAME),
   foreign key (CUSTOMER_ID) references CUSTOMERS(ID)

stay Customer Class , mapping Customer Class images The code for the property is as follows :

  private Set<String> images=new HashSet<String>();

@ElementCollection Annotations are used to map collection types images attribute ,@CollectionTable Annotation assignment images Sets correspond to IMAGES Database table ,joinColumns Attribute specifies IMAGES Tabular CUSTOMER_ID Foreign key reference CUSTOMERS Main table .@Column Annotation assignment images Each element in the set corresponds to IMAGES Tabular FILENAME Field .

By default , Yes Customer Object's images Attribute adopts delayed retrieval strategy . If immediate retrieval strategy is needed , Can pass @ElementCollection Annotated fetch Property to set :


 Insert picture description here