I have a simple Spring-Hibernate application. I have 3 classes crop, market and farmer with structure something like :
class crop
{
private int cropId;
}
class market
{
private int marketId;
}
class farmer
{
private Crop crop;
private Market market;
}
farmer table has a composite key{cropid, marketid}.
Now, how do I map this relationship with composite key element cropid
and marketid
referencing to crop and market table respectively in the .hbm.xml
file .
I am quite new to hibernate and spring. Any suggestions will 开发者_C百科be of great help !!
In the farmer.hbm.xml you need to make a composite-id
like this
<composite-id class="FarmerId" mapped="true">
<key-property name="cropid"/>
<key-property name="marketid"/>
</composite-id>
and write a class FarmerID
that implements Serializable
and overrides equals()
and hashCode()
In equals()
you test if the Objects are the same or have the same values and return a boolean. In hashCode()
you generate a hash value and return it.
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if ((obj == null) || (obj.getClass() != this.getClass()))
return false;
FarmerID test = (FarmerID) obj;
boolean flagCrop = cropid == test.cropid;
boolean flagMarket = marketid == test.marketid;
return flagCrop && flagMarket;
}
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + cropid.hashCode();
hash = 31 * hash + marketid.hashCode();
return hash;
}
精彩评论