I am using Hibernate 3, and I have a very basic relationship of a Employee and Address class:
Code:
<hibernate-mapping>
<class
name="org.appfuse.model.Employee"
table="EMPLOYEES">
<id
name="empnumber"
column="EMPNUMBER"
type="java.lang.Long">
<generator class="increment"/>
</id>
<property
name="surname"
type="java.lang.String"
update="true"
insert="true"
column="SURNAME"
length="50"
not-null="true"
/>
<property
name="forenames"
type="java.lang.String"
update="true"
insert="true"
column="FORENAMES"
length="100"
not-null="true"
/>
<one-to-one
name="employeesAddress"
class="org.appfuse.model.EmployeesAddress"
cascade="all"
outer-join="auto"
constrained="false"
/>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class
name="org.appfuse.model.EmployeesAddress"
table="EMPLOYEES_ADDRESS">
<id
name="employeesNumber"
column="EMPLOYEES_NUMBER"
type="java.lang.Long">
<generator class="assigned"/>
</id>
<property
name="address1"
type="java.lang.String"
update="true"
insert="true"
column="ADDRESS_1"
length="50"
not-null="true"
/>
<property
name="address2"
type="java.lang.String"
update="true"
insert="true"
column="ADDRESS_2"
length="50"
/>
<property
name="postcode"
type="java.lang.String"
update="true"
insert="true"
column="POSTCODE"
length="20"
/>
</class>
</hibernate-mapping>
I have a situation where I have to add the Employee and their Address in one save i.e.
Code:
Employee employee = new Employee();
employee.setForenames(applicant.getForenames());
employee.setSurname(applicant.getSurname());
ApplicantAddress applicantAddress = applicant.getApplicantAddress();
EmployeesAddress employeesAddress = new EmployeesAddress();
employeesAddress.setAddress1(applicantAddress.getAddress1());
employeesAddress.setAddress2(applicantAddress.getAddress2());
employeesAddress.setPostcode(applicantAddress.getPostcode());
employee.setEmployeesAddress(employeesAddress);
getHibernateTemplate().saveOrUpdate(employee);
However, I receive the error:
Quote:
ids for this class must be manually assigned before calling save(): org.appfuse.model.EmployeesAddress; nested exception is org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): org.appfuse.model.EmployeesAddress
This as I undertstand is because Hibernate does not save the Employee, retrieve it's new id and populate that into EmployeeAddress and consequently save that.
What is the best solution for this? I cannot seem to find a way retreiving the id of Employee after insert, nor to find a way of Hibernate to automatically cascade the update whilst managing the id's.
Any help would be greatly appreciated.
Regards,
Peter