views:

74

answers:

1

Hello,

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.

In my ClassA I have the following:

@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

@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. Why is the PK missing? How can I define it?

I use JPA 2.0 Hibernate implementation, if this helps.

Thanks.

A: 

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.

So if you want to generate its composite primary key, you should split your @ManyToMany into @OneToMany-@ManyToOne relationship. 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

// 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

See whether objectsB property in ClassA contains me and, if so, save our relationship in objectA_objectB table

Arthur Ronald F D Garcia
@Arthur Ronald F D Garcia It still happen the same with mappedBy
Javi