Hibernate: map M:N relationships with references to classes instead
of ID's ?
Hi,
I've been trying to implement a many-to-many relationship in
a JobHistory class related to my JOB_HISTORY table with
the following (excerpt from my JobHistory.hbm.xml):
....
<class name="JobHistory" table="JOB_HISTORY">
<composite-id>
<!--following OK-->
<!--<key-property name="empId" access="field" type="long"
column="EMPLOYEE_ID" />-->
<!--<key-property name="jobId" access="field" type="string"
column="JOB_ID" />-->
<!--following fails:-->
<key-property name="emp" access="Employee" type="object"
column="EMPLOYEE_ID" />
<key-property name="job" access="Job" type="object"
column="JOB_ID" />
</composite-id>
....
The first 2 lines commented above in my .hbm.xml mapping file
run fine (with 'long'/'String' variables for empId and jobId in my
class),
but when I try to replace these numeric references to class
references and specify an access="<class name>" and -of course-
modify my JobHistory class accordingly:
...
//Long empId;
Employee emp;
//String jobId;
Job job;
public JobHistory() {}
//public JobHistory(Long eid, String jid) {
public JobHistory(Employee eid, Job jid) {
emp=eid; job=jid;
}
... etc.)
I get the following runtime error:
~ identifier mapping has wrong number of columns: \
~ test.JobHistory type: component[emp,job]
In JOB_HISTORY the JOB_ID column is a VARCHAR2(10). The fields
that form the key are of different types. This table implements
the M:N relationship between my EMPLOYEES and JOBS table.
In my class MainTest I have:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 Employee e = getEmployee(200L);
2 Job j = getJob(14);
3 JobHistory jh = new JobHistory();
4 jh.setEmp(e);
5 jh.setJob(j);
6 jh.setStartDate(new java.util.Date...);
7 jh.setEndDate(new java.util.Date...);
8 Session s = sf.getCurrentSession();
9 Transaction t = s.beginTransaction();
10 s.save(jh);
11 t.commit();
(getEmployee and getJob are methods containing a small
HQL query returning respectively the Employee and the Job
with ID's 200 and 14 in the database)
Is there a way to avoid playing directly with ID's ?
I'd like to avoid jh.setEmpId(e.getId()) and jh.setJobId(j.getId())
at lines 4 and 5 above...
I found no solution for mapping this in JobHistory.hbm.xml.
In advance, thanks.
Spendius