简体   繁体   English

ManyToMany Relation不创建主键

[英]ManyToMany Relation does not create the primary key

I have a ManyToMany relationship between two classes: ClassA and ClassB, but when the table for this relationship (table called objectA_objectB) there is no primary key on it. 我在两个类之间有一个ManyToMany关系:ClassA和ClassB,但是当这种关系的表(称为objectA_objectB的表)上没有主键时。

In my ClassA I have the following: 在我的ClassA中,我有以下内容:

@ManyToMany(fetch=FetchType.LAZY)
@OrderBy(value="name")
@JoinTable(name="objectA_objectB",
        joinColumns=
            @JoinColumn(name="idObjectA", referencedColumnName="id"),
        inverseJoinColumns=
            @JoinColumn(name="idObjectB", referencedColumnName="id")
)
private List<ClassB> objectsB;

and in my ClassB I have the reversed relation 在我的ClassB中,我有相反的关系

@ManyToMany
List<ClassA> objectsA;

I just want to make a primary key of both id's but I need to change the name of the columns as I do. 我只想同时创建两个ID的主键,但需要像我一样更改列的名称。 Why is the PK missing? 为什么PK不见了? How can I define it? 我该如何定义?

I use JPA 2.0 Hibernate implementation, if this helps. 如果有帮助,我将使用JPA 2.0 Hibernate实现。

Thanks. 谢谢。

You are right 你是对的

I have done the same approach as shown by your question. 我已经按照您的问题所示的方法进行了处理。 And, indeed, Hibernate does not generate its composite primary key as expected. 而且,实际上,Hibernate不会按预期生成其复合主键。

So if you want to generate its composite primary key, you should split your @ManyToMany into @OneToMany-@ManyToOne relationship. 因此,如果要生成其复合主键,则应将@ManyToMany拆分为@ OneToMany- @ ManyToOne关系。 See here how to... 看到这里如何...

UPDATE 更新

When you have a bi-directional relationship, you must set up the inverse side of the relationship by using mappedBy attribute 当您具有双向关系时,必须使用mappingBy属性设置关系的反面

// ClassA

@ManyToMany(fetch=FetchType.LAZY)
@JoinTable(name="objectA_objectB",
    joinColumns=
        @JoinColumn(name="idObjectA", referencedColumnName="id"),
    inverseJoinColumns=
        @JoinColumn(name="idObjectB", referencedColumnName="id")
)
private List<ClassB> objectsB;

... ...

// ClassB

// You do not specify the foreign key column here (it is mapped by the other side)
@ManyToMany(mappedBy="objectsB")
List<ClassA> objectsA;

mappedBy="objectsB" says appedBy =“ objectsB”说

See whether objectsB property in ClassA contains me and, if so, save our relationship in objectA_objectB table 查看ClassA中的objectsB属性是否包含我,如果包含,则将我们的关系保存在objectA_objectB表中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM