public class Menu {
  private int menuId;
  private String name;
  private Set<Item> items=new HashSet<Item>();

}
public class Item {
  private int itemId;
  private String name;
  private Float weight;
  private Set<Menu> menus=new HashSet<Menu>();
}


重量的属性应在第三个表“ menu_item”中。

菜单的xml

<class name="Menu" table="menu">
    <id name="menuId" type="java.lang.Integer" column="menuId">
        <generator class="increment"></generator>
    </id>
    <property name="name" type="string" column="menuName" length="100"></property>
    <set access="property" lazy="true" inverse="false" cascade="save-update"
        name="items" batch-size="10" fetch="select" table="menu_item">
        <key column="menuId" />
        <many-to-many class="Item" column="itemId" />
    </set>


项目的xml:

<class name="Item" table="item">
    <id name="itemId" type="java.lang.Integer" column="itemId">
        <generator class="increment"></generator>
    </id>
    <property name="name" type="string" column="itemName" length="100"></property>
    <set access="property" lazy="true" inverse="false" cascade="save-update"
        name="menus" batch-size="10" fetch="select" table="menu_item">
        <key column="itemId" />
        <many-to-many class="Menu" column="menuId" />
    </set>
</class>


mysql中的第三个表menu_item:
menuId,itemId,重量

但是如何获得重量的价值?我可以在菜单的xml中写一些东西吗?

最佳答案

您需要为第三个表创建一个新实体(MenuItem):

<class name="MenuItem" table="menu_item" mutable="false">
   <composite-id name="id" class="MenuItem$Id">
     <key-property name="menuId" access="field" column="menu_id"/>
     <key-property name="itemId" access="field" column="item_id"/>
   </composite-id>
   <property name="weight" column="weight" type="string" not-null="true"/>
   <many-to-one name="menu" column="menu_id" not-null="true" insert="false" update="false"/>
   <many-to-one name="item" column="item_id" not-null="true" insert="false" update="false"/>
</class>


您的映射将从多对多变为一对多,例如:

<set name="items" inverse="true">
   <key column="item_id"/>
   <one-to-many class="MenuItem"/>
</set>


另一种方法是将MenuItem类设置为@Embeddable并映射组件的集合:

<class name="Menu" table="menu">
   <set name="menuItems" table="menu_item">
       <key column="menu_id"/>
       <composite-element class="MenuItem">
           <parent name="menu"/>
           <many-to-one name="item" column="menu_id" not-null="true" class="Item"/>
           <property name="weight" column="weight"/>
        </composite-element>
   </set>
</class>

08-18 00:10