You are currently browsing the daily archive for October 8, 2008.

@Many-To-Many annotation

@Target({METHOD, FIELD}) @Retention(RUNTIME)

public @interface ManyToMany {

Class targetEntity() default void.class;

CascadeType[] cascade() default {};

FetchType fetch() default LAZY;

String mappedBy() default “”;

}

1. Bidirectional Many-To-Many relationship

@Entity

@Table(name=”CATEGORIES”)

public class Category implements Serializable {

@Id

@Column(name=”CATEGORY_ID”)

protected Long categoryId;

protected String name;

@ManyToMany

@JoinTable(name=”CATEGORIES_ITEMS”,

joinColumns=

@JoinColumn(name=”CI_CATEGORY_ID”,

referencedColumnName=”CATEGORY_ID”),

inverseJoinColumns=

@JoinColumn(name=”CI_ITEM_ID”,

referencedColumnName=”ITEM_ID”))

protected Set<Item> items;

}

@Entity

@Table(name=”ITEMS”)

public class Item {

@Id

@Column(name=”ITEM_ID”)

protected Long itemId;

protected String title;

@ManyToMany(mappedBy=”items”)

protected Set<Category> categories;

}

2. Composite Primary Key

@Embeddable

public class CategoryPK {

String name;

Date createDate;

public CategoryPK() {}

public boolean equals(Object other) {

if (other instanceof CategoryPK) {

final CategoryPK otherCategoryPK = (CategoryPK)other;

return (otherCategory.name.equals(name) &&

otherCategoryPK.createDate.equals(createDate));

}

return false;

}

public int hashCode() {

return super.hashCode();

}

}

@Entity

public class Category {

public Category() {}

@EmbeddedId

protected CategoryPK categoryPK;

}

Advertisements