是一对多,多对一双向相同,多对多?

时间:2016-03-17 07:49:01

标签: hibernate

是一对多,多对一的双向同样在hibernate中实现多对多的方式?

@Entity
@Table(name="ITEM")
public class Item { ... } // no relational mapping here

@Entity
@Table(name = "CART")
public class Cart {
    @ManyToMany(targetEntity = Item1.class, cascade = { CascadeType.ALL })
    @JoinTable(name = "CART_ITEMS", //  name of physical database table
                joinColumns = { @JoinColumn(name = "cart_id") }, 
                inverseJoinColumns = { @JoinColumn(name = "item_id") })
    private Set<Item1> items;
} 

通过使用mappedBy,我只有两个物理表(ITEM和CART):

@Entity
@Table(name="ITEM")
public class Item {
    @ManyToOne(name = "cart", nullable = false, insertable=false, updatable=false)
    private Cart cart;
}

@Entity
@Table(name = "CART")
public class Cart {
    @OneToMany(mappedBy = "cart")
    private Set<Item> items;
} 

但是通过使用@JoinTable,连接两者的物理表也将是CART_ITEMS。同样多对多。

@Entity
@Table(name="ITEM")
public class Item {
    @ManyToOne(name = "cart", nullable = false, insertable=false, updatable=false)
    private Cart cart;
}

@Entity
@Table(name = "CART")
public class Cart {
    @OneToMany
    @JoinTable( name = "CART_ITEMS",
        joinColumns = @JoinColumn(name = "CART_ID"),
        inverseJoinColumns = @JoinColumn(name = "ITEM_ID") )
    private Set<Item> items;
} 

1 个答案:

答案 0 :(得分:0)

不,创建的数据库表和添加到这些表的约束都存在差异。在您的第一种情况@ManyToMany中,创建的三个表是Cart,Item和CartItem连接表:

create table CART1 (id bigint not null, primary key (id))
create table CART1_ITEMS1 (cart1_id bigint not null, item1_id bigint not null, primary key (cart1_id, item1_id))
create table ITEM1 (id bigint not null, primary key (id))

约束允许ManyToMany映射,只要求条目指向Cart或Item表中的现有条目:

alter table CART1_ITEMS1 add constraint FK_rp3ydw070costp3hxxipfdepm foreign key (item1_id) references ITEM1
alter table CART1_ITEMS1 add constraint FK_lj0kor79pdsabd7oeuvpbc1vv foreign key (cart1_id) references CART1

在OneToMany双向表中,表几乎相同,只是Item表中包含了一个foreign key的购物车表。

create table CART3 (id bigint not null, primary key (id))
create table CART3_ITEMS3 (CART3_ID bigint not null, ITEM3_ID bigint not null, primary key (CART3_ID, ITEM3_ID))
create table ITEM3 (id bigint not null, cart3_id bigint, primary key (id))

约束包含unique约束,可阻止任何Item引用多个Cart

alter table CART3_ITEMS3 add constraint UK_kmbin3nr6yh9pn8p11vfd75rf  unique (ITEM3_ID)
alter table CART3_ITEMS3 add constraint FK_kmbin3nr6yh9pn8p11vfd75rf foreign key (ITEM3_ID) references ITEM3
alter table CART3_ITEMS3 add constraint FK_8mjsk05vejc18afjorn4d8gbw foreign key (CART3_ID) references CART3

以及Item表上需要有效Cart引用的约束。

alter table ITEM3 add constraint FK_exbk5pj0g8jllcxfsvmsr88if foreign key (cart3_id) references CART3

希望这有帮助。