@ManyToMany

From CauchoWiki

Jump to: navigation, search


The @ManyToMany relation represents a unidirectional link to a collection of entity beans. In the database, it is represented by a join table with foreign keys to the source entity and to the target entity.

The property type must be a collection.

 @ManyToMany
 public Collection<ChildBean> getChildren() { return _children; }

Contents

[edit] Annotation Definition

 public @interface ManyToMany {
     Class targetEntity() default void.class;
     CascadeType []cascade() default {};
     FetchType []fetch() default EAGER;
     String mappedBy() default "";
 }

The targetEntity gives the class name of the target entity bean. If unspecified, it defaults to the item type of the collection.

The CascadeType selects operations that are cascaded to the target when the source bean is modified.

The EAGER FetchType is a hint to Amber that the field should be fetched along with the rest of the entity. The LAZY fetch type is a hint that Amber can wait until the field is used before loading it from the database.

The optional value indicates that the field is Nullable in the database. Java primitives are never optional.

[edit] Optional Annotations

The following annotations can be used in combination with @ManyToMany.

[edit] Column names

If a @JoinTable is specified with a @ManyToMany property, the @JoinTable's name specifies the name of the join table. If there is no @JoinTable, the join table name is constructed from the source table and the target table name.

    public class SourceBean {
       @Id
       public int getId() { ... }

       @ManyToMany
       public Collection<TargetBean> getChildren()
   }
   public class TargetBean {
         @Id 
         String getName() { return _name; }
   }

The join table name would be SOURCEBEAN_TARGETBEAN, and the default foreign keys would be "SOURCEBEAN_ID" and "TARGETBEAN_ID".

[edit] Example: unidirectional @ManyToMany with specified SQL

   @Entity
   @Table(name="s")
   public class Src {
       @Id 
       @Column(name="s_id")
       int getId() { ... }
 
       @ManyToMany
       @JoinTable(name="map",
                  joinColumns={@JoinColumn(name="s_key")},
                  inverseJoinColumns={@JoinColumn(name="d_key")})
       Collection<Dst> getChildren() { ... }
   }

   @Entity
   @Table(name="d")
   public class Dst {
       @Id
       @Column(name="d_id")
       int getId() { ... }
    }
   create table s (
       s_id integer primary key
   )
   
   create table d (
       d_id integer primary key
   )

   create table map (
       s_key integer references(s, s_id),

       d_key integer references(d, d_id)
   )
Personal tools