Piccione,
Yes, you can achieve a many-to-many relationship using composite primary keys instead of the single-column, meaningless ID.
What you do is to mix the recommendations of Chapter 7 of the reference, where they teach you about "Association Mappings", with Chapter 8 of the reference, where they teach you about Component Mapping with multiple keys.
Here's a working example: Suppose you have 2 main tables, A and C.
You want to create a many-to-many relationship between them, so you use a relation table B.
Both main tables A and C have composite primary keys. In order to represent that, you create 2 small classes, PKA and PKC. This is how your code would look like (I suppress the getters and setters for brevity, and assume it to be unidirectional only)
Code:
public class A {
private APK idA;
private Set<C> cs=new HashSet<C>();
}
Code:
public class C {
private CPK idC;
}
Code:
public class APK implements Serializable{
String ak1;
String ak2;
}
Code:
public class CPK implements Serializable{
private String ck1;
private String ck2;
}
This would be a mapping file that achieves what you want
Code:
<hibernate-mapping package="test5" >
<class name="A" table="A">
<composite-id name="idA" class="APK">
<key-property name="ak1"/>
<key-property name="ak2"/>
</composite-id>
<set name="cs" table="B">
<key>
<column name="ak1"/>
<column name="ak2"/>
</key>
<many-to-many class="C">
<column name="ck1"/>
<column name="ck2"/>
</many-to-many>
</set>
</class>
<class name="C" table="C">
<composite-id name="idC" class="CPK">
<key-property name="ck1"/>
<key-property name="ck2"/>
</composite-id>
</class>
</hibernate-mapping>
And these would be the corresponding tables (DDL):
create table A (ak1 varchar(255) not null, ak2 varchar(255) not null, primary key (ak1, ak2))
create table B (ak1 varchar(255) not null, ak2 varchar(255) not null, ck1 varchar(255) not null, ck2 varchar(255) not null, primary key (ak1, ak2, ck1, ck2))
create table C (ck1 varchar(255) not null, ck2 varchar(255) not null, primary key (ck1, ck2))
alter table B add constraint FK42AB395985 foreign key (ak1, ak2) references A
alter table B add constraint FK42AB39688B foreign key (ck1, ck2) references C