有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在hibernate集合中包含外键的java复合键

我不明白如何在一个集合中定义一个复合键,包括一个外键

这里是我的目标:

MyObject                    MySubset
--------                    -------------
String myId                 String subAttribute
String myAttribute          String subValue
Set<MySubset> mySubset

我想要两个表MyObjectTableMySubsetTablemyIdMyObjectTable的主键。我想将FKmyId子属性定义为MySubsetTable的组合键

xml中的hibernate映射是什么样子的

<hibernate-mapping>
  <class table="myObjectTable" name="MyObject">
    <id name="myId">
      <column name="myId"/>
    </id>
    <property name="myAttribute"> <column name=....> </property>
    <set cascade="all, delete-orphan table="MySubsetTable" name"mySubset" ...>

      <!-- How should I define my key? -->


      <composite-element class="MySubset">
        <property name="subAttribute"> <column name="subAttribute"/> </property>
        <property name="subValue"> <column name="subValue"/> </property>
      </composite-element>
    </set>
  </class>
</hibernate-mapping>

共 (1) 个答案

  1. # 1 楼答案

    我解决问题的方法不是使用集合,而是使用地图:

    <hibernate-mapping>
      <class table="myObjectTable" name="MyObject">
        <id name="myId">
          <column name="myId"/>
        </id>
        <property name="myAttribute"> <column name=....> </property>
        <map cascade="all, delete-orphan table="MySubsetTable" name"mySubset" ...>
          <key not-null="true" foreign-key="FK_MyObj" column="MyObject"/>
          <map-key type="string" column="myAttribute"/>
          <element type="string" column="myValue"/>
        </map>
      </class>
    </hibernate-mapping>
    

    也许这对其他人有帮助