"映射中的重复列用于收集" forHibernate ManyToMany使用相同的外键?

时间:2016-09-29 10:29:29

标签: java hibernate jpa many-to-many

我有4张表格如下:

create table market (
    id int(6) unsigned auto_increment primary key,
    market_id varchar(30) unique
);

create table market_channel_group (
    id int(6) unsigned auto_increment primary key,
    market_id varchar(30),
    channel_group_id varchar(30),
    unique index (market_id,channel_group_id)
);

create table market_channel (
    id int(6) unsigned auto_increment primary key,
    market_id varchar(30),
    channel_id varchar(30),
    unique index (market_id,channel_group_id)
);

create table market_channel_group_detail (
    id int(6) unsigned auto_increment primary key,
    market_id varchar(30),
    channel_group_id varchar(30),
    channel_id varchar(30),
    unique index (market_id,channel_group_id, channel_id)
);

正如您所看到的,市场是OneToMany到market_channel_group,market_channel。 market_channel_group是ManyToMany在特定市场下的market_channel。

问题出在我的market_channel_group实体中,我有以下代码:

@Entity(name = "market_channel_group")
@Table(name = "market_channel_group", uniqueConstraints = {@UniqueConstraint(columnNames = {"market_id", "channel_group_id"})})
public class MarketChannelGroup extends BaseEntity {

    private static final long serialVersionUID = 1L;

    public MarketChannelGroup() {
        super();
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private int id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "market_id", referencedColumnName = "market_id")
    private Market market;

    @Column(name = "channel_group_id", length = 50)
    private String channelGroupId;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "market_channel_group_detail",
            joinColumns = {@JoinColumn(name = "market_id", referencedColumnName = "market_id"), @JoinColumn(name = "channel_group_id", referencedColumnName = "channel_group_id")},
            inverseJoinColumns = {@JoinColumn(name = "market_id", referencedColumnName = "market_id"), @JoinColumn(name = "channel_id", referencedColumnName = "channel_id")})
    private List<MarketChannel> channels;

...
}

然而,我遇到了这个例外:

Caused by: org.hibernate.MappingException: Repeated column in mapping for collection: MarketChannelGroup.channels column: market_id
    at org.hibernate.mapping.Collection.checkColumnDuplication(Collection.java:343) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
...

我应该如何正确编写ManyToMany注释?或者我的设计有任何问题。

更新

因为我们将从外部资源导入数据,所以自动增量ID不会被用作其他表格&#39;引用,每个表都有另一个索引而不是它自己的id。

1 个答案:

答案 0 :(得分:0)

对我来说,可以通过在insertable = false, updatable = false上添加@JoinColumn来解决。