Need help with Hibernate? Read this first:
http://www.hibernate.org/ForumMailingli ... AskForHelp
Hibernate version:3.2.1
I'm trying to figure out a straightforward way of mapping a class with a composition to another class using a HashMap.
Seems straight forward, but i'm having a little problem.
Consider Company maintains a collection of Branches, keyed by the BranchName;
I would like to map this in such a way that there should only be 2 tables, Company and Branch.
The Branch Table may or may not need it's own synthetic key, i can certainly see a key consisting of
CompanyID,BranchName being unique, and of course used to establish the Map. The CompanyId could also serve
as the one-to-one reference from the Branch back to the Company.
I've got something working with the collection mapping looking like below. However, the branch table has it's own ID, which really isn't necessary. What
I'd rather is that the CompanyID,BranchName is the key, and the map is loaded using them.
Am i missing something? or is this really very exotic?
Code:
<class name=Company ...>
<map name="Branches" inverse="true" cascade="all" >
<key column="companyID" not-null="true" />
<map-key type="string" column="BranchName" />
<one-to-many class="Branch" />
</map>
</class>
<class name = Branch ...>
<id name="branchID" type="long">
<generator class="native"/>
</id>
<many-to-one name="company" not-null="true" column="companyID" class="Company" />
</class>
Code:
class Company{
private Long companyID;
private String companyName;
private String companyOther;
private Map<String,Branch>branches = new HashMap<String,Branch>();
private Map<String, Branch> getBranches() {
return branches;
}
private void setBranches(Map<String, Branch> branches) {
this.branches = branches;
}
public void setBranch(Branch branch){
branches.put(branch.getBranchName(), branch);
branch.setCompany(this);
}
public Branch getBranch(String branchName){
return branches.get(branchName);
}
public Long getCompanyID() {
return companyID;
}
public void setCompanyID(Long companyID) {
this.companyID = companyID;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyOther() {
return companyOther;
}
public void setCompanyOther(String companyOther) {
this.companyOther = companyOther;
}
}
class Branch{
private Long branchID;
private String branchName;
private String branchOther;
private Company company;
private Long getBranchID() {
return branchID;
}
public void setBranchID(Long branchID) {
this.branchID = branchID;
}
public String getBranchName() {
return branchName;
}
public void setBranchName(String branchName) {
this.branchName = branchName;
}
public String getBranchOther() {
return branchOther;
}
public void setBranchOther(String branchOther) {
this.branchOther = branchOther;
}
public Company getCompany() {
return company;
}
private void setCompany(Company company) {
this.company = company;
}
}