Hello, I have a doubt about map some classes with Hibernate 3.3.x and I can't resolve myself. It's very frustrating... hope somebody can light me the way.
Domain description
I have 3 classes ('Company', 'Branch' and 'Employee') and these requirements:
- A company has one or more branch.
- A company has one or more employees. (Company has a set of employees)
- An employee could work in one or more branches. (A branch has a set of employees, of course these employees belongs to the company)
Classes
Code:
public class Company {
private Set<Branch> branches = new HashSet<Branch>();
private Set<Employee> employees = new HashSet<Employee>();
...
}
Code:
public class Branch {
private Set<Employee> employees = new HashSet<Employee>();
...
}
Code:
public class Employee {
...
}
Hibernate mapping Code:
<class name="Company" table="COMPANIES">
<id name="id" column="ID">
<generator class="native"/>
</id>
<set name="branches" table="COMPANIES_BRANCHES" lazy="true">
<key column="COMPANY_ID"/>
<many-to-many column="BRANCH_ID" class="Branch"/>
</set>
<set name="employees" table="COMPANIES_EMPLOYEES" lazy="true">
<key column="COMPANY_ID"/>
<many-to-many column="EMPLOYEE_ID" class="Employee"/>
</set>
</class>
Code:
<class name="Branch" table="BRANCHES">
<id name="id" column="ID">
<generator class="native"/>
</id>
<set name="employees" table="BRANCHES_EMPLOYEES" lazy="true">
<key column="BRANCH_ID"/>
<many-to-many column="EMPLOYEE_ID" class="Employee"/>
</set>
</class>
Code:
<class name="Employee" table="EMPLOYEES">
<id name="id" column="ID">
<generator class="native"/>
</id>
</class>
My problem Well, according to my database design -structure generated by Hibernate- I could have an employee assigned to a branch that does't belong to any company. To avoid this problem maybe one solution could be having a table with composite keys like this:
Code:
CREATE TABLE `EMPLOYEES_PER_BRANCH` (
`COMPANY_ID` bigint(20) NOT NULL,
`BRANCH_ID` bigint(20) NOT NULL,
`EMPLOYEE_ID` bigint(20) NOT NULL,
PRIMARY KEY (`COMPANY_ID`,`BRANCH_ID`,`EMPLOYEE_ID`),
CONSTRAINT `FK_COMPANY` FOREIGN KEY (`COMPANY_ID`) REFERENCES `companies` (`ID`),
CONSTRAINT `FK_BRANCH` FOREIGN KEY (`BRANCH_ID`) REFERENCES `branches` (`ID`),
CONSTRAINT `FK_EMPLOYEE` FOREIGN KEY (`EMPLOYEE_ID`) REFERENCES `employees` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
That table could fix my problem, but I don't know how should I map my classes to have that result. I have been read all Hibernate documentation but I am still confusing.
I know very well that according Hibernate and ORM philosophy I should model my problem thinking in objects and forgetting relational tables, I am doing that, but this problem is present and I don't know how to avoid it.
Maybe I am modelling or mapping my classes in the wrong way inside *.hbm.xml files? Maybe have a table like I say it's a bad solution for my problem?.
Hope someone can help me in my doubt.
Thanks a lot to all Hibernate community!
Greetings