My hibernate version is 3.0.3
SUN JDK 1.4.2
Oracle 8.1.7
Windows XP,
What I want to do is to use a non primary key property as the map key in a many-to-many relations with using collection table.
In our scenario, a Company can have many different types of Phone, such as main contact phone, fax number, and so on. Meanwhile, Company has primary key "company_name", and Phone has phone_id as primary key.
Though there is a map collection relation example under org.hibernate.test.map in hibernate, it's using the child class's primary property as map key, not what I want. I wonder if hibernate support this feature.
The following java code and hibernate mapping
(NOT WORKING) can show what I mean. How can config the map relation to make it works?
Code:
public class Company {
private String companyName;
private Map phones=new HashMap();
public Phone getPhoneBy(String phoneType) {
(Phone)phones.get(phoneType);
}
public void addPhone(String phoneType, Phone newPhone) {
phones.put(phoneType,newPhone);
}
//....
}
public class Phone {
private int id;
private String phoneNumber;
//...
}
<!-- Hibernate mapping -->
<class name="Company" table="COMPANY">
<id name="companyName"/>
<map name="phones" cascade="persist" table="COMPANY_PHONE">
<key column="COMPANY_NAME"/>
<map-key formula="PHONE_TYPE" type="string"/>
<many-to-many column="PHONE_ID" class="Phone"/>
</map>
</class>
<class name="Phone" table="PHONE">
<id name="id"/>
<property name="phoneNumber"/>
</class>