如何从Hibernate的第三个表中获取属性?

时间:2011-11-05 03:12:31

标签: java hibernate spring struts2 hql

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>

item的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,weight

但我怎样才能获得体重的价值?我可以在菜单的xml中写一些东西吗?

1 个答案:

答案 0 :(得分:1)

您需要为第三个表创建一个新实体(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>