How do I define a many-to-many bidirectional relationship between two entities? I have tried and failed all the time. It looks like such a common case and I am surprised to see that it is not working.
I have two entities Country and Language and they form a many-to-many relationship which is bidirectional. I want to represent it as Map on both the sides. Country will have a map of languageName Vs Language where languageName is the column in Language table. Similarly Language will have a map of CountryCode Vs Country where CountryCode is the column in Country table.
Somehow Hibernate always looks for the languageName and CountryCode column in the link Table i.e CountryLanguage and not the respective tables.
Here is the mapping for the two entities
Country.hbm.xml
-----------------
Code:
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernatetest.a82545.Country" lazy="true" table="Country">
<id name="CountryId" type="int">
<column length="10" name="CountryId"/>
<generator class="native"/>
</id>
<property name="CountryCode" type="string">
<column length="2" name="CountryCode" not-null="true"/>
</property>
<map name="Languages" table="CountryLanguage" cascade="all">
<key column="CountryId"/>
<map-key column="LanguageName" type="string"/>
<many-to-many class="hibernatetest.a82545.Language" column="LanguageId"/>
</map>
</class>
</hibernate-mapping>
Language.hbm.xml
-----------------
Code:
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernatetest.a82545.Language" lazy="true" table="`Language`">
<id name="LanguageId" type="int">
<column length="10" name="LanguageId"/>
<generator class="native"/>
</id>
<property name="LanguageName" type="string">
<column name="LanguageName" not-null="true"/>
</property>
<map inverse="true" name="Countries" table="CountryLanguage">
<key column="LanguageId"/>
<map-key column="countrycode" type="string" />
<many-to-many class="hibernatetest.a82545.Country" column="CountryId"/>
</map>
</class>
</hibernate-mapping>
Is this even supported?