Why am I getting Mapping Exception?

烂漫一生 提交于 2019-12-02 11:49:26

For a ManyToMany Relationshhip you need a dedicated mapping table

6.2.4. Collections of values and many-to-many associations

i.e. You need something like a PersonAddress Table

CREATE TABLE personaddress (p_id integer, a_id integer)

Where p_id is a FK Reference to the Person Table and a_id a FK Reference to the Address Table

You need to specify different table name for many-to-many association as it's handled by a separate table:

<class name="pojo.Person" table="person">
      <id column="p_id" name="personID">
          <generator class="increment" />
      </id>
      <property name="personName" column="p_name" />
      <set name="addressSet" table="person_address" cascade="all">
          <key column="p_id" />
          <many-to-many class="pojo.Address" column="a_id" />
      </set>
</class>

Note that <set> now references to person_addresses table. With default configuration, Hibernate is able to create it automatically.

There's another mistake that I see: ID generator for Address entity should not be foreign, it's usually used in 1-to-1 relationships (uses ID of another associated object). You can use the same 'increment' use used for Person entity:

<class name="Address" table="address">
    <id column="a_id" name="addressID">
        <generator class="increment" />
    </id>
    <property name="address" column="address" />
</class>

You need to create a reference table:

    CREATE TABLE PersonsAddresses (personId BIGINT, addressId BIGINT)

and change the mapping of the set to this:

    <set name="addressSet" table="PersonsAddresses" order-by="personId">
        <key column="personId" foreign-key="p_id"/>
        <many-to-many column="addressId" node="a_id" class="pojo.Address" />
    </set>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!