many-to-many

//-----------------------------关联表---------------------------------
@Entity
@Table(name = "CATEGORY_ITEM")
@org.hibernate.annotations.Immutable
public class CategorizedItem {
//使用符合主键
    @Embeddable
    public static class Id implements Serializable {
    @Column(name = "CATEGORY_ID")
    protected Long categoryId;
    @Column(name = "ITEM_ID")
    protected Long itemId;
    public Id() {
    }
    public Id(Long categoryId, Long itemId) {
    this.categoryId = categoryId;
    this.itemId = itemId;
    }
    public boolean equals(Object o) {
        if (o != null && o instanceof Id) {
            Id that = (Id) o;
            return this.categoryId.equals(that.categoryId)
                && this.itemId.equals(that.itemId);
        }
        return false;
    }
    public int hashCode() {
        return categoryId.hashCode() + itemId.hashCode();
    }
    @Column(updatable = false)
    @NotNull
    protected String addedBy;
    @Column(updatable = false)
    @NotNull
    protected Date addedOn = new Date(); F Maps timestamp

    //映射为OneToMany
    @ManyToOne
    @JoinColumn(
    name = "CATEGORY_ID",insertable = false, updatable = false)
    protected Category category; G Maps category
    @ManyToOne
    @JoinColumn(
    name = "ITEM_ID",insertable = false, updatable = false)
    protected Item item; H Maps item

    //值id,由程序生成
    @EmbeddedId
    protected Id id = new Id();
public CategorizedItem(
    String addedByUsername,
    Category category,
    Item item) {
    this.addedBy = addedByUsername;
    this.category = category;
    this.item = item;
    this.id.categoryId = category.getId();
    this.id.itemId = item.getId();
    category.getCategorizedItems().add(this);
    item.getCategorizedItems().add(this);
    }
// ...
}

//-------------------------两个多对多实体-----------------------------------
@Entity
public class Category {
    //放弃管理
    @OneToMany(mappedBy = "category")
    protected Set<CategorizedItem> categorizedItems = new HashSet<>();
    // ...
}
@Entity
public class Item {
@OneToMany(mappedBy = "item")
protected Set<CategorizedItem> categorizedItems = new HashSet<>();
// ...
}

//-------------------------------持久化---------------------------------

Category someCategory = new Category("Some Category");
Category otherCategory = new Category("Other Category");
em.persist(someCategory);
em.persist(otherCategory);
Item someItem = new Item("Some Item");
Item otherItem = new Item("Other Item");
em.persist(someItem);
em.persist(otherItem);
CategorizedItem linkOne = new CategorizedItem(
"johndoe", someCategory, someItem
);
CategorizedItem linkTwo = new CategorizedItem(
"johndoe", someCategory, otherItem
);
CategorizedItem linkThree = new CategorizedItem(
"johndoe", otherCategory, someItem
);
em.persist(linkOne);
em.persist(linkTwo);
em.persist(linkThree);
posted @ 2016-05-21 23:16  fcat  阅读(128)  评论(0编辑  收藏  举报