View Javadoc
1   package ejava.examples.orm.rel.annotated;
2   
3   import java.util.ArrayList;
4   import java.util.Collection;
5   
6   import javax.persistence.*;
7   
8   /**
9    * This class is used as an example of a @OneToMay, using a join table. In
10   * this example, the Inventory has a OneToMany relationship with Media. The
11   * navigation is uni-directional from Inventory to Media and the MEDIA table
12   * has no foreign key to reference the INVENTORY table. An INVENTORY_MEDIA
13   * join (or link) table is used to make the linkage.
14   */
15  @Entity @Table(name="ORMREL_INVENTORY")
16  public class Inventory {
17      @Id @GeneratedValue
18      private long id;
19      private String name;
20  
21      @OneToMany(cascade={CascadeType.ALL})
22      //@JoinTable(name="ORMREL_INVENTORY_MEDIA")  //places FK to this and Media in link table
23      @JoinColumn(name="INVENTORY_ID")             //places FK to this in Media 
24      private Collection<Media> media = new ArrayList<Media>();
25      
26      public Inventory()        {}
27      public Inventory(long id) { this.id = id; }
28      
29      public long getId() { return id; }
30  
31      public Collection<Media> getMedia() { return media; }
32      public void setMedia(Collection<Media> media) {
33          this.media = media;
34      }
35  
36      public String getName() { return name; }
37      public void setName(String name) {
38          this.name = name;
39      }
40  
41      private String myInstance() {
42          String s=super.toString();
43          s = s.substring(s.lastIndexOf('.')+1);
44          return s;
45      }
46  
47      public String toString() {
48          StringBuilder text = new StringBuilder(myInstance());
49          text.append(", id=" + id);
50          text.append(", name=" + name);
51          text.append(", media(" + media.size() + ")={");
52          for(Media m: media) {
53              text.append(m.getId() + ",");
54          }
55          text.append("}");
56          return text.toString();
57      }
58  }